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

      

  • 相关阅读:
    MySQL——索引
    MySQL——逻辑分层与存储引擎
    APP测试总结
    如何提高测试的质量
    测试用例的基础
    opencv图像处理常用操作一
    【bug】【Cannot find reference 'imread' in '__init__.py | __init__.py'】
    Numpy学习笔记
    工业互联网
    Python基本的数据清洗
  • 原文地址:https://www.cnblogs.com/zhaoyansheng/p/5024584.html
Copyright © 2011-2022 走看看