LeetCode No. 1 issue: two numbers

This article first appeared in the public number "five minutes learning algorithm", is illustrated LeetCode one of a series of articles.

Website: www.cxyxiaowu.com

Video explain: [] followed by a programmer named Wu illustration LeetCode LeetCode No. 1 issue: two numbers

The title comes from LeetCode first No. 1 issue: two numbers. Item difficulty is Easy, the current pass rate of 45.8%.

Title Description

Given an array of integers numsand a target value target, and you find that the target value in the array of two integers, and return to their array subscript.

You can assume that each input corresponds to only one answer. However, you can not re-use the same array element.

Example:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
复制代码

Analytical title

Using a lookup table to solve the problem.

A map is provided to record the value of the index container element of the record, and then through the array nums.

  • When using a temporary variable to save complement each iteration the current value of the difference between the target value and
  • Find record in the traversal, see if there is a consistent and complement values, if the search is successful value index to find the value of the current variable i is returned
  • If not found, then the record and save the element index i

Animation description

Code

// 1. Two Sum
// https://leetcode.com/problems/two-sum/description/
// 时间复杂度:O(n)
// 空间复杂度:O(n)
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> record;
        for(int i = 0 ; i < nums.size() ; i ++){
       
            int complement = target - nums[i];
            if(record.find(complement) != record.end()){
                int res[] = {i, record[complement]};
                return vector<int>(res, res + 2);
            }

            record[nums[i]] = i;
        }
    }
};

复制代码

Reproduced in: https: //juejin.im/post/5cef814151882503050edddd

Guess you like

Origin blog.csdn.net/weixin_33720956/article/details/91463282