zoukankan      html  css  js  c++  java
  • Two Sum -- leetcode

    Two Sum – leetcode
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.
    You may assume that each input would have exactly one solution.
    Example:
    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    注意:这里返回的是数组的下标而不是数组中的元素。

    分析:
    如果还是用两个指针的方法求解的话,需要记录其排序之前和之后的位置对应关系。
    在这里可以采用哈希表来解决问题,假定一个加数已经在数组中了(循环遍历),也知道最终的和,那么 根据 和 - 加数 = 被加数 ,只需要判断被加数是否在哈希表中即可。
    哈希表的键值为:<数组元素,对应的下标>
    因为哈希表查找的时间复杂度为O(nlogn),所以最终时间复杂度为O(nlogn)
    代码:

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
            // 利用Map构造Hash表
            map<int, int> Hash;
            for (int i =0; i< nums.size(); i++){
                Hash[nums[i]] = i;
            }
    
            // 依次遍历第一个加数
            vector<int> ans(2);
            for (int i=0; i<nums.size(); i++){
            // 当存在对应的被加数,而且这个加数不是自己时侯——找到了一组解
                if (Hash.find(target - nums[i]) != Hash.end() && Hash[target - nums[i]] != i){
                    ans[0] = i;
                    ans[1] = Hash[target - nums[i]];
                    break;
                }
            }
            return ans;
        }
    };
    
    不积跬步,无以至千里;不积小流,无以成江海。
  • 相关阅读:
    JDK 1.7.0 安装后,如何配置,以及如何打开JAR文件
    C++中的内存!(转载)堆 栈 全局/static变量区 常量区
    学习.net应该知道什么
    SQL Group By
    编码
    ASP生成静态Html文件技术杂谈
    如何写出优秀的ASP应用
    DropDownList的绑定方法
    如何提高WEB程序的效率
    什么才是提高ASP性能的最佳选择
  • 原文地址:https://www.cnblogs.com/xiaocai-ios/p/7779786.html
Copyright © 2011-2022 走看看