leetcode题解-167. Two Sum II

来源:互联网 发布:mysql防注入 编辑:程序博客网 时间:2024/04/28 16:21

题目:

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.Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2

其实和Two Sum一样,只不过给的数组是排好序的而已,且返回索引从1开始,所以我们提出下面三种解决方案:

  1. 双指针法
  2. map法
  3. binary search法

第一种方法,两个指针分别从0和length-1开始遍历,然后求和两个数,如果等于target就返回,如果大于则right–,否则left++。代码如下所示:

    public int[] twoSum(int[] numbers, int target) {        int [] res = new int [2];        int left = 0, right = numbers.length-1;        while(left < right){            int tmp = numbers[left] + numbers[right];            if(tmp == target){                res[0] = left + 1;                res[1] = right + 1;                break;            }else if(tmp < target)                left ++;            else                right --;        }        return res;    }

另外一种方法就是使用map来保存遍历过的数组信息,与Two Sum原理相同。代码入下:

    public int[] twoSum1(int[] numbers, int target) {        Map<Integer, Integer> map = new HashMap<>();        int [] res = new int[2];        for(int i=0; i<numbers.length; i++){            if(map.containsKey(numbers[i])){                res[0] = map.get(numbers[i]);                res[1] = i+1;                break;            }else                map.put(target-numbers[i], i+1);        }        return res;    }

方法三是使用binary search,其实跟方法一思路很相近,这里就不再进行赘述。

0 0
原创粉丝点击