• 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 };
  • 相关阅读:
    nginx.conf nginx反向代理配置文件
    linux shell date的用法
    shell find 命令 find命令报错 find: paths must precede expression:
    nginx平滑升级
    centos 6/7 tar包安装mysql 5.7
    3. Longest Substring Without Repeating Characters
    模板之类模板2
    排序之归并排序
    排序之堆排序
    排序之选择排序
  • 原文地址:https://www.cnblogs.com/panda_lin/p/two_sum.html
Copyright © 2020-2023  润新知