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 }
  • 相关阅读:
    bat过滤任意字符
    汇编代码之修改文件时间
    使用C语言编写提取通用shellcode的程序
    汇编代码之修改文件时间
    VC++6.0中内存泄漏检测
    透视木马程序开发技术
    bat过滤任意字符
    VC++6.0中内存泄漏检测
    透视木马程序开发技术
    使用C语言编写提取通用shellcode的程序
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4856032.html
Copyright © 2011-2022 走看看