zoukankan      html  css  js  c++  java
  • LeetCode-001题解

    此题目摘自LeetCode001

    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 
    

      初看此题,首先想到的是暴力求解法,两个for循环嵌套,遍历寻找满足target的两个数。时间复杂度为O(n2)。其实此题还有一个O(n)的解法。十分巧妙。

      先上代码(Java版本)

    public class Solution {
        public int[] twoSum(int[] nums, int target) {
            int len = nums.length;
            Map<Integer, Integer> m = new HashMap<Integer, Integer>();
            for(int i = 0; i < len; ++i){
                if(m.get(nums[i]) != null){
                    return new int[] {(Integer)m.get(nums[i])+1, i + 1};
                }else{
                    m.put(target - nums[i], i);
                }
            }
            return null;
        }
    }
    

      代码很简短,但是理解起来比较抽象。大意是现在HashMap中寻找nums,没有找到,就把target-nums[i]以及下标i作为键值对存入m中。如果找到了,说明在m中有当前的数值刚好对应m存贮的target的余值。

    另外贴上C++版本的题解。意义一样

    class Solution {
    public:
    vector<int> twoSum(vector<int> &num, int target) {
    map<const int,int> m;
    int s = num.size();
    for(int i=0;i<s;i++){
        if(m.find(num[i])!= m.end()){
           vector<int> vec;
           int pos = m[num[i]];
           vec.insert(pos);
           vec.insert(i+1);
           return vec;
        }
        else{
             m.insert(pair<int, int> (target -num[i], i+1));
        }
    }
    }
    };
    

      

  • 相关阅读:
    SSL工作原理
    xmlhttprequest对象
    form验证的图片(小技巧)
    C#转码
    引用不了App_Code里的类
    再谈如何成为技术领袖
    如何做好年末总结?
    编程习惯
    软件人员推荐书目(都是国外经典书籍!!!)
    又当爹又当妈的产品经理
  • 原文地址:https://www.cnblogs.com/zhaoyansheng/p/5024584.html
Copyright © 2011-2022 走看看