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 }
  • 相关阅读:
    应用文档iOS, 在应用之间共享文档。
    项目范围项目管理项目范围管理
    网站教程一些学习网站
    布局文件Android ListView入门知识各种Adapter配合使用
    随波逐流希望2013年半年小总结(复杂艰难的半年)
    安全微软微软安全新闻聚焦双周刊第三十二期
    对象类《大话设计模式》部分模式总结(一):
    循环跳转JAVA Continue实例详解
    节点程序寻找链表倒数第k个节点
    box2d编译
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4856032.html
Copyright © 2011-2022 走看看