剑指offer57.和为s的两个数字

剑指offer57.和为s的两个数字_第1张图片

双指针i从左往右,j从右往左,如果大于目标值,j往左走否则i往右走,直到等于目标值

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        int i = 0; int j = nums.length-1;
        int sum = nums[i] + nums[j];
        while(sum != target){
            if(sum > target){j--;}else if(sum < target){i++;} 
            sum = nums[i] + nums[j];  
        }
        res[0] = nums[i]; res[1]=nums[j];
       return res;
       }
    }

你可能感兴趣的:(剑指offer,leetcode,算法)