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));
        }
    }
    }
    };
    

      

  • 相关阅读:
    数据结构与算法部分习题题解
    Codeforces Round #372 +#373 部分题解
    KMP算法的正确性证明及一个小优化
    后记
    BZOJ 4089:[Sdoi2015]graft(SDOI 2015 Round 2 Day 2)
    BZOJ 4085:[Sdoi2015]bigyration(SDOI 2015 round 2 Day 1)
    使用 async await 封装微信小程序HTTP请求
    mongo创建数据库和用户
    把实体bean对象转换成DBObject工具类
    Trident整合MongoDB
  • 原文地址:https://www.cnblogs.com/zhaoyansheng/p/5024584.html
Copyright © 2011-2022 走看看