[LeetCode]1. Two Sum ❤

来源:互联网 发布:java程序员技能要求 编辑:程序博客网 时间:2024/06/17 17:49

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.

Example:

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

______________________________ 以上摘自LeetCode题目

看到题目首先想到的就是二重循环,打出来发现竟然不会超时↓

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        int size = nums.size();        for (int i = 0; i < size - 1; ++i) {            for (int j = i + 1; j < size; ++j) {                if (nums[i] + nums[j] == target) {                    vector<int> r;                    r.push_back(i);                    r.push_back(j);                    return r;                }            }        }    }};
如果想要降低时间复杂度呢?把二重循环减为一次遍历:先算出target和nums[i]的差值,再去在nums中寻找是否有该值。

可以把nums存进一个map中,nums的元素值作为key而下标作为value。再对该map进行二分查找,找是否有那个差值。

原创粉丝点击