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

      

  • 相关阅读:
    webgame模块划分
    VC的若干实用小技巧(一)
    反病毒技术:从亡羊补牢到免疫防御
    MySQL 备份和恢复
    企业网络安全整体解决方案
    大型银行核心网络的三层结构设计
    编写"优美"的SHELLCODE
    linux中apache访问控制配置文件。
    网站同步镜像制作!
    Linux远程桌面(vnc)
  • 原文地址:https://www.cnblogs.com/zhaoyansheng/p/5024584.html
Copyright © 2011-2022 走看看