[LeetCode] #167# Two Sum II : 数组/二分查找/双指针

一. 题目
1. Two Sum II

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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 
二. 题意
  • 给定一个有序数组和一个目标值
  • 找出数组中两个成员,两者之和为目标值,并顺序输出
  • 假设一定存在一个解

 

三. 分析

  • 算法核心:
    • 三种方法:
      • 暴力搜索: 时间复杂度 O(n^2) (超时)
      • 哈希表: 时间复杂度 O(n)
      • 二分查找: 时间复杂度 O(nlogn)
      • 使用双指针分别指向数组头和尾,同时双向遍历数组: 时间复杂度 O(n)
  • 实现细节:
    • 算法逻辑相对简单
    • 实现细节相对容易

 

四. 题解

  • 哈希表
    • 实现
 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& A, int target) {
 4         vector<int> res;
 5         int n = A.size();
 6         map<int, int> m;
 7                 
 8         for (int i = 0; i < n; i++) m[A[i]] = i + 1;
 9         
10         for (int i = 0; i < n; i++) {
11             if (0 != m.count(target - A[i]) && i + 1 != m[target - A[i]]) {
12                 res.push_back(i + 1);
13                 res.push_back(m[target - A[i]]);
14                 return res;
15             }
16         }
17         
18         return res;       
19     }
20 };
    • 结果

 

  • 二分查找
    • 实现
 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& A, int target) {
 4         vector<int> res;
 5         int n = A.size();
 6         
 7         for (int i = 0; i < n; i++) {
 8             int left = i + 1, right = n - 1;
 9             while (left <= right) {
10                 int mid = (left + right) / 2;
11                 if (A[mid] < target - A[i]) left = mid + 1;
12                 else if (A[mid] > target - A[i]) right = mid - 1;
13                 else {res.push_back(i + 1); res.push_back(mid + 1); return res;}
14             }
15         }
16 
17         return res;       
18     }
19 };
    • 结果

 

  • 双指针
    • 实现
 1 class Solution {
 2 public: 
 3     vector<int> twoSum(vector<int>& A, int target) {
 4         vector<int> res;
 5         int left = 0, right = A.size() - 1;
 6 
 7         while (left < right) {
 8             if (A[left] + A[right] < target) left++;
 9             else if (A[left] + A[right] > target) right--;
10             else {res.push_back(left + 1), res.push_back(right + 1); return res;};
11         }
12         
13         return res;       
14     }
15 };
    • 结果

 

五. 相似题

posted on 2016-06-12 16:28  zhongyuansh  阅读(579)  评论(0编辑  收藏  举报

导航