zoukankan      html  css  js  c++  java
  • 【Two Sum】cpp

    题目

    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

    代码

    class Solution {
    public:
        vector<int> twoSum(vector<int> &numbers, int target) {
            std::vector<int> ret_vector;
            std::map<int,int> value_index;
            for (int i = 0; i < numbers.size(); ++i)
            {
                const int gap = target - numbers[i];
                if (value_index.find(gap) != value_index.end())
                {
                    ret_vector.push_back(std::min(i+1,value_index[gap]+1));
                    ret_vector.push_back(std::max(i+1,value_index[gap]+1));
                    break;
                }
                else
                {
                    value_index[numbers[i]] = i; 
                }
            }
            return ret_vector;
        }
    };

    Tips:

    元素无序且要求复杂度O(n)的,就可以用hashmap解决。

    网上有的算法先遍历一遍numbers获得所有元素的map<value,index>,再进行后续的计算。这样的算法没有考虑数组元素重复的case

    比如:

    numbers = [0,2,4,0]

    target = 0

    ===========================================

    第二次过此题,大体思路非常明确。额外开一个hashmap,访问数组一次就搞定。

    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target) {
                vector<int> ret;
                unordered_map<int, int> value_index;
                for ( int i=0; i<nums.size(); ++i )
                {
                    if ( value_index.find(target-nums[i])!=value_index.end() )
                    {
                        ret.push_back(i+1);
                        ret.push_back(value_index[target-nums[i]]+1);
                        break;
                    }
                    value_index[nums[i]] = i;
                }
                std::sort(ret.begin(), ret.end());
                return ret;
        }
    };

    tips:

    有三个细节需要注意:

    1. [3, 2, 4] 6 对于这种类型的,一定要把value_index[nums[i]]=i放在if语句的后面,要不然同一个元素3就被用了两次

    2. 题目要返回的index并不是数组下标,而是数组下标加1,且返回的值要求有序

  • 相关阅读:
    定时任务的分布式调度
    springmvc 静态资源 配置
    activemq 持久化
    函数式编程与面向对象编程的比较
    LeetCode 108——将有序数组转化为二叉搜索树
    LeetCode 104——二叉树中的最大深度
    LeetCode 700——二叉搜索树中的搜索
    线性代数之——四个基本子空间
    线性代数之——线性相关性、基和维数
    线性代数之——秩和解的结构
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4437052.html
Copyright © 2011-2022 走看看