LeetCode - 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. 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=9
Output: index1=1, index2=2
public class Solution { public int[] twoSum(int[] arr, int k) { List<Integer> ret = new ArrayList<Integer>(); int head = 0, tail = arr.length-1; while (arr[head] <= k/2) { if (arr[head]+arr[tail] == k) { ret.add(head+1); ret.add(tail+1); break; } else if (arr[head]+arr[tail] < k) { head ++; } else tail --; } return toArr(ret); } private int[] toArr(List<Integer> arr) { int[] ret = new int[arr.size()]; for (int i=0; i<arr.size(); i++) { ret[i] = arr.get(i); } return ret; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。