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,且返回的值要求有序

  • 相关阅读:
    html5css练习 旋转
    html5 css练习 画廊 元素旋转
    html5 渐变按钮练习
    html5 旋转导航练习
    html5 javascript 表单练习案例
    html5 p1练习1,移动页面,标准标签布局
    pyqt5desinger的安装即配置
    python 文件操作
    openGL 大作业之n星变换
    openGL 蓝天白云
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4437052.html
Copyright © 2011-2022 走看看