zoukankan      html  css  js  c++  java
  • leetcode: Two Sum

    http://oj.leetcode.com/problems/two-sum/

    Given an array of integers, 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

    思路

    排序后两个指针一个从前往后,一个从后往前逼近。需要小心的是当输入数组可有重复的数字,所以需要先保存每个数字在哪些位置出现过以备查询。

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int> &numbers, int target) {
     4         vector<int> result;
     5         map<int, vector<int> > indexes;
     6         int i, j, size = numbers.size();
     7         
     8         for (i = 0; i < size; ++i) {
     9             indexes[numbers[i]].push_back(i + 1);
    10         }
    11         
    12         sort(numbers.begin(), numbers.end());
    13         i = 0; 
    14         j = size - 1;
    15         
    16         while (i < j) {
    17             if ((numbers[i] + numbers[j]) < target) {
    18                 ++i;
    19             }
    20             else if ((numbers[i] + numbers[j]) > target) {
    21                 --j;
    22             }
    23             else {
    24                 vector<int>::iterator left = indexes[numbers[i]].begin();
    25                 vector<int>::iterator right = indexes[numbers[j]].begin();
    26                 
    27                 if (left == right) {
    28                     ++right;
    29                 }
    30                 
    31                 result.push_back((*left < *right) ? *left : *right);
    32                 result.push_back((*left < *right) ? *right : *left);
    33                 
    34                 break;
    35             }
    36         }
    37         
    38         return result;
    39     }
    40 };
  • 相关阅读:
    SQLite(快速上手版)笔记
    自定义带图片和文字的ImageTextButton
    Android 网络连接判断与处理
    Android轻量缓存框架--ASimpleCache
    Mvc4_ActionLink跟@RenderBody ,@RenderPage
    Mvc4_传值取值应用
    Mvc4_ActionResult应用
    IIS_Mvc发布
    IIS_各种问题
    SqlServer_事务
  • 原文地址:https://www.cnblogs.com/panda_lin/p/two_sum.html
Copyright © 2011-2022 走看看