zoukankan      html  css  js  c++  java
  • 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 NOTzero-based.

     Notice

    You may assume that each input would have exactly one solution

    Example

    numbers=[2, 7, 11, 15], target=9

    return [1, 2]

    Analyse: Be aware of that one element could appear more than once. Map each element into an array.

    Runtime: 10ms

     1 class Solution {
     2 public:
     3     /*
     4      * @param numbers : An array of Integer
     5      * @param target : target = numbers[index1] + numbers[index2]
     6      * @return : [index1+1, index2+1] (index1 < index2)
     7      */
     8     vector<int> twoSum(vector<int> &nums, int target) {
     9         // write your code here
    10         
    11         // use a hash map to store array information
    12         // the key is element in nums, value is the index of that element
    13         unordered_map<int, vector<int> > um; 
    14         for (int i = 0; i < nums.size(); i++) {
    15             um[nums[i]].push_back(i);
    16         }
    17         
    18         // scan the array and find if (target - element) in the hash map
    19         vector<int> result;
    20         for (int i = 0; i < nums.size(); i++) {
    21             if (um.find(target - nums[i]) != um.end()) {
    22                 // a value appears more than once and happens to equal to half of target
    23                 if (nums[i] == target - nums[i]) {
    24                     result.push_back(um[nums[i]][0] + 1);
    25                     result.push_back(um[nums[i]][1] + 1);
    26                 }
    27                 else {
    28                     int index1 = um[nums[i]][0], index2 = um[target - nums[i]][0];
    29                     result.push_back(min(index1, index2) + 1);
    30                     result.push_back(max(index1, index2) + 1);
    31                 }
    32                 break;
    33             }
    34         }
    35         return result;
    36     }
    37 };
  • 相关阅读:
    bash中一次性给多个变量赋值命名管道的使用
    Mysql复制还原后root帐号权限丢失问题
    TC中HTB的使用备注
    Python 调用JS文件中的函数
    PIL图像处理模块,功能强大、简单易用(转)
    openfeign 实现动态Url
    Extjs 进度条的应用【转】
    Javascript 对象与数组中的函数下【转】
    Linq学习笔记之一:Linq To XML
    Sql Server查询语句的一些小技巧
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/5797193.html
Copyright © 2011-2022 走看看