两数之和 II - 输入有序数组 (Two Sum II - Input Array Is Sorted)

 

思路:双指针

// @Title: 两数之和 II - 输入有序数组 (Two Sum II - Input Array Is Sorted)
// @Author: qisiii
// @Date: 2022-03-10 19:34:13
// @Runtime: 1 ms
// @Memory: 44.4 MB
// @comment: 双指针
// @flag: BLUE
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result=new int[2];
        int left=0,right=numbers.length-1;
        while(left<right){
            if(numbers[left]+numbers[right]==target){
                result[0]=left+1;
                result[1]=right+1;
                break;
            }else if(numbers[left]+numbers[right]<target){
                left++;
            }else{
                right--;
            }
        }
        return result;
    }
}

思路:垃圾暴力

// @Title: 两数之和 II - 输入有序数组 (Two Sum II - Input Array Is Sorted)
// @Author: qisiii
// @Date: 2022-03-10 19:29:48
// @Runtime: 362 ms
// @Memory: 44 MB
// @comment: 垃圾暴力
// @flag: RED
class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int[] result=new int[2];
        for(int i=0;i<numbers.length;i++){
            int temp=target-numbers[i];
            for(int j=i+1;j<numbers.length;j++){
                if(numbers[j]==temp){
                    result[0]=i+1;
                    result[1]=j+1;
                    return result;
                }
            }
        }
        return result;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18