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 };
  • 相关阅读:
    集群、分布式、负载均衡区别与联系
    Android--加载大分辨率图片到内存
    Android--MP3播放器MediaPlayer
    Android--SoundPool
    Android--MediaPlayer高级
    Android--调用系统照相机拍照与摄像
    Android--SurfaceView播放视频
    Android--使用VideoView播放视频
    Android--使用Camera拍照
    Vue组件选项props
  • 原文地址:https://www.cnblogs.com/panda_lin/p/two_sum.html
Copyright © 2011-2022 走看看