Leetcode 167

2017-12-21  本文已影响9人  柯原哀

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

要求

这道题是给定一个值target,然后求升序数组中是否存在两个元素的值相加等于target,如果相等的话返回对应的索引值加1(规定下标从1开始).不存在的话返回[0,0]。而且规定总是只有一种解法,数组中的元素只能遍历一次。

解题思路

因为数组只能遍历一次,所以分别设置左指针lef和右指针right,求num[left]和num[right]的和sum,如果这个和等于target,则返回left+1和right+1。如果sum>target,则右指针right--,反之左指针left++。

反思

自己总想着遍历每个数组需要用到for循环,其实设置指针根据情况自增自减同样可以实现。

public int [] twoSum(int [] num, int targte){
  
        int[] indice = new int[2];
        
        if (num == null || num.length < 2) {return indice;}
        
        int left = 0, right = num.length - 1;
   
        while (left < right) {
         
            int sum= num[left] + num[right];
            if (sum == target) {
            indice[0] = left + 1;
            indice[1] = right + 1;
            break;
        } else if (sum > target) {
            right --;
        } else {
            left ++;
        }
    }
     return indice;
    }

}
上一篇下一篇

猜你喜欢

热点阅读