zoukankan      html  css  js  c++  java
  • LeetCode OJ: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

    给一个vector,一个value,要求求出vector之内的两数相加之和等于value的两个index。

    这里的基本思想是用一个map先来保存vector元素的值与他们对应的index,然后循环vector,用value减去每个数之后,把差值直接放到map里面去寻找
    看能不能找到对应的index,大体上就是这个思想,下面详见代码:

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         map<int, int> index;
     5         vector<int> result;
     6         int sz = nums.size();
     7         for (int i = 0; i < sz; ++i){
     8             index[nums[i]] = i;
     9         }
    10         map<int, int>::iterator it;
    11         for (int i = 0; i < sz; ++i){
    12             if ((it = index.find(target - nums[i])) != index.end()){
    13                 if (it->second == i) continue;//这一步要注意,防止找到的index与当前的i是相等的
    14                 result.push_back(i + 1);
    15                 result.push_back(it->second + 1);
    16                 break;
    17             }
    18         }
    19         return result;
    20     }
    21 };

     附上java版本的代码,方法比上面简洁一点。不过道理还是基本一样的:

     1 public class Solution {
     2     public int[] twoSum(int[] nums, int target) {
     3         HashMap<Integer, Integer> m = new HashMap<Integer, Integer>();
     4         int [] result = new int[2];
     5         for(int i = 0; i < nums.length; ++i){
     6             if(m.containsKey(nums[i])){
     7                 int index = m.get(nums[i]);
     8                 result[0] = index + 1;
     9                 result[1] = i + 1;
    10                 break;
    11             }else{
    12                 m.put(target-nums[i] ,i);//很关键!
    13             }
    14         }
    15         return result;
    16     }
    17 }
  • 相关阅读:
    VS2008 Ajax Toolkit 控件(修正后转载)
    AD操作类[修改版]
    java中使用Rhino执行js文件中的function
    XSTL中单引号的问题
    [转]ADSearch User Property Attributes
    2008我的健身计划
    spring执行定时任务
    分页存储过程,支持多表查询,效率还行
    今天写一个读卡器程序,操作AD时的一个Exception:The authentication mechanism is unknown
    httpclient模拟windows认证
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4856032.html
Copyright © 2011-2022 走看看