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 };
  • 相关阅读:
    django 模板继承
    redis集群环境配置
    压力测试工具:apache bench(ab)
    php yield关键字以及协程的实现
    php图片木马实现原理
    关于接口幂等性
    关于easyswoole实现websocket聊天室的步骤解析
    php混淆加密解密实战
    关于mysql集群主从服务器搭建
    mysql binlog恢复数据实战
  • 原文地址:https://www.cnblogs.com/panda_lin/p/two_sum.html
Copyright © 2011-2022 走看看