【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

时间: 2024-11-09 10:27:06

【Two Sum】cpp的相关文章

【Path Sum】cpp

题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ 7 2 1 return true,

【Combination Sum 】cpp

题目: Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target) w

【Minimum Path Sum】cpp

题目: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 代码: class Solution { public:

【Binary Tree Maximum Path Sum】cpp

题目: Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For example:Given the below binary tree, 1 / 2 3 Return 6. 代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode

【Maximum Subarray 】cpp

题目: Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4],the contiguous subarray [4,−1,2,1] has the largest sum = 6. 代码: class Solution { public:

【Add binary】cpp

题目: Given two binary strings, return their sum (also a binary string). For example,a = "11"b = "1"Return "100". 代码: class Solution { public: string addBinary(string a, string b) { std::string result; std::string::reverse_iter

【Word Break】cpp

题目: Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words. For example, givens = "leetcode",dict = ["leet", "code"]. Return true becau

【Sudoku Solver】cpp

题目: Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. 代码: cla

【Subsets II】cpp

题目: Given a collection of integers that might contain duplicates, nums, return all possible subsets. Note: Elements in a subset must be in non-descending order. The solution set must not contain duplicate subsets. For example,If nums = [1,2,2], a sol