這道題自己不難,我認爲關鍵是要給出靠譜的證實。方法是先排序,而後首末各放一個指針進行移動。若是小了,左指針向右移,若是大了,右指針向左移。指針
證實應該就是要靠數學概括法,證實每次正確答案應該在移動以後的兩個指針之間。code
public class Solution { public int[] twoSum(int[] nums, int target) { // 1. sort List<Integer> inputs = new ArrayList<Integer>(); for (int num : nums) { inputs.add(num); } Collections.sort(inputs); // 2. iterate int length = nums.length; int p = 0; int q = length - 1; while (p < q) { if (inputs.get(p) + inputs.get(q) < target) { p++; } else if (inputs.get(p) + inputs.get(q) > target) { q--; } else { break; } } for (int i = 0; i < length; i++) { if (nums[i] == inputs.get(p)) { p = i; break; } } for (int i = length - 1; i >= 0; i--) { if (nums[i] == inputs.get(q)) { q = i; break; } } int result[] = {p,q}; return result; } }