package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * @ClassName: TwoSum2 * @Author: xiaof * @Description: 167. Two Sum II - Input array is sorted * 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. * * Input: numbers = [2,7,11,15], target = 9 * Output: [1,2] * Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. * * @Date: 2019/7/2 10:22 * @Version: 1.0 */ public class TwoSum2 { public int[] solution(int[] numbers, int target) { //求两数之和就是对应的target,并且反馈对应的下标 int index1 = 0, index2 = 0; //这里其实也是遍历,但是已知target,那么我们每次只要获取到第一个数据的下表,然后对后面的数据进行二分查找判断是否有对应的数据就可以了 for(int i = 0; i < numbers.length; ++i) { index1 = i; int num1 = numbers[i]; //二分查找目标 int targetNum = target - num1; int start = i + 1, end = numbers.length - 1; while(start < end) { int mid = start + ((end - start) >>> 1); if(numbers[mid] == targetNum) { index2 = mid; break; } else if (numbers[mid] > targetNum) { //如果目标位置比目标数据大,说明要找的数据在前面 end = mid; } else { //如果比目标数据小,说明再后面,然后我们mid的位置已经做了比较,所以后移一位 //因为mid = start + (end - start) >>> 1; 可能正好等于start start = mid + 1; } } if(start == end) { //如果首尾相等,那么手动判断一下 if(targetNum == numbers[start]) { index2 = start; } } if(index2 != 0) { break; } } int result[] = new int[2]; result[0] = index1 + 1; result[1] = index2 + 1; return result; } //网上大牛最快,也是占内存最小的算法,有点类似快排的思想 public int[] twoSum(int[] numbers, int target) { int []res = new int [2]; int index1 = 0; int index2 = numbers.length - 1; while (index2 > index1){ if (numbers[index1] + numbers[index2] > target){ index2 --; } else if(numbers[index1] + numbers[index2] < target){ index1 ++; }else{ res[0] = index1+1; res[1] = index2+1; break; } } return res; } public static void main(String args[]) { int pres[] = {5,25,75}; int target = 100; System.out.println(new TwoSum2().solution(pres, target)); } }
【LEETCODE】38、167题,Two Sum II - Input array is sorted
猜你喜欢
转载自www.cnblogs.com/cutter-point/p/11119433.html
今日推荐
周排行