码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】

时间:2018-09-22 14:26:26      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:ble   哈希   vector   shm   hid   style   cafe   tail   order   

1. Two Sum

【题目】https://leetcode.com/problems/two-sum/description/

【思路】将数组 利用 map 处理 即可

【代码】

技术分享图片
 1 class Solution {
 2 public:
 3     vector<int> twoSum(vector<int>& nums, int target) {
 4         // 哈希表存储 值->下标 的映射
 5         unordered_map<int, int> indices;
 6         
 7         for (int i = 0; i < nums.size(); i++)
 8         {
 9             int temp = target - nums[i];
10             if (indices.find(temp) != indices.end() && indices[temp] != i)
11             {
12                 return vector<int> {indices[temp], i};
13             }
14             indices.emplace(nums[i], i);
15         }
16     }
17 };
C++
技术分享图片
 1 class Solution {
 2     public int[] twoSum(int[] nums, int target) {
 3         Map<Integer, Integer> indeces = new HashMap<>();
 4         for(int i=0;i<nums.length;++i) {
 5             int temp = target - nums[i];
 6             if(indeces.containsKey(temp)) {
 7                 return new int[] {indeces.get(temp), i};
 8             }
 9             indeces.put(nums[i], i);
10         }
11         return null;
12     }
13 }
Java

【get】

C++中 HashMap 的使用

https://blog.csdn.net/charles1e/article/details/52042066

 

【leetcode】

标签:ble   哈希   vector   shm   hid   style   cafe   tail   order   

原文地址:https://www.cnblogs.com/chsobin/p/9689721.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!