LeetCode 1 Two Sum

xiaoxiao2021-02-28  40

LeetCode 1

Two Sum

Reference:http://blog.csdn.net/liyuanbhu/article/details/51050095

Problem Description: 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, and you may not use the same element twice.

Examples: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].

Solution:

class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<int> result; map<int, int> group; for (int i = 0; i < nums.size(); i++) { group[nums[i]] = i; } for (int i = 0; i < nums.size()-1; i++) { int value = target-nums[i]; if (group.count(value) && group[value] != i) { result.push_back(i); result.push_back(group[value]); break; } } return result; } };
转载请注明原文地址: https://www.6miu.com/read-2620384.html

最新回复(0)