leetcode笔记—Array

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode笔记—Array相关的知识,希望对你有一定的参考价值。

1. Two Sum

找到数组中和为target的两个数,返回索引

技术分享图片
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].
problem
技术分享图片
 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         unordered_map<int, int> hash;
 5         vector<int> result;
 6         for (int i = 0; i < nums.size(); i++) {
 7             if (hash.find(target - nums[i]) != hash.end()) {
 8                 result.push_back(hash[target - nums[i]]);
 9                 result.push_back(i);
10                 return result;
11             }
12             hash[nums[i]] = i;
13         }
14         return result;
15     }
16 };
View Code




















以上是关于leetcode笔记—Array的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode——array EASY笔记

leetcode解题笔记--part1--array

leetcode笔记:Search in Rotated Sorted Array

Leetcode刷题笔记-数组

LeetCode与《代码随想录》哈希表篇:做题笔记与总结-JavaScript版

js代码片段: utils/lcoalStorage/cookie