1. 程式人生 > >LeetCode 167. Two Sum II - Input array is sorted (兩數之和之二 - 輸入的是有序數組)

LeetCode 167. Two Sum II - Input array is sorted (兩數之和之二 - 輸入的是有序數組)

point find leetcode algorithm 個數 tar div solution runtime

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


題目標簽:Array, Two Pointers

  題目給了我們一個array, 和一個 target, array 是遞增排列的,讓我們找到兩個數字 之和 等於 target。 這裏要返回的是 它們的index, 不過是從1開始的。

  利用two pointers, 一個left = 0, 一個 right = numbers.length - 1, 因為array 是遞增排列的, 所以當 left 數字 + right 數字 大於 target 的話,說明 之和太大了,需要更小的數字,所以把 right-- 來拿到更小的數字;

  當left 數字 + right 數字 小於 target 的話, 說明 之和太小了, 需要更大的數字, 所以要把 left++ 來拿到更大的數字;

  當 left 數字 + right 數字 等於target 的話,直接返回 index + 1。

Java Solution:

Runtime beats 44.34%

完成日期:04/06/2017

關鍵詞:Array, Two Pointers

關鍵點:了解 兩數之和 與 target 的比較下 兩個指針該如何移動,建立在遞增array的情況下

 1 public class Solution 
 2 {
 3     public
int[] twoSum(int[] numbers, int target) 4 { 5 int left = 0, right = numbers.length-1; 6 int res[] = new int[2]; 7 8 while(left < right) 9 { 10 // find two numbers 11 if((numbers[left] + numbers[right]) == target) 12 { 13 res[0] = left + 1; 14 res[1] = right + 1; 15 break; 16 } 17 else if((numbers[left] + numbers[right]) > target) // if greater, right moves to left 1 place 18 right--; 19 else // if less, left moves to right 1 place 20 left++; 21 22 } 23 24 return res; 25 } 26 }

參考資料:

http://www.cnblogs.com/ganganloveu/p/4198968.html

LeetCode 算法題目列表 - LeetCode Algorithms Questions List

LeetCode 167. Two Sum II - Input array is sorted (兩數之和之二 - 輸入的是有序數組)