167. Two Sum II - Input array is sortedjava
題目大意:和Two Sum同樣,這裏給出的數組是有序的數組
思路:target - nums[i],這樣就實現了降維了code
Java實現:ip
public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target - nums[i])) { result[1] = i + 1; result[0] = map.get(target - nums[i]) + 1; return result; } map.put(nums[i], i); } return result; }
別人的實現:leetcode
public int[] twoSum(int[] num, int target) { int[] indice = new int[2]; if (num == null || num.length < 2) return indice; int left = 0, right = num.length - 1; while (left < right) { int v = num[left] + num[right]; if (v == target) { indice[0] = left + 1; indice[1] = right + 1; break; } else if (v > target) { right --; } else { left ++; } } return indice; }