1. Two Sum
Posted blackyao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1. Two Sum相关的知识,希望对你有一定的参考价值。
Kotlin
class Solution {
fun twoSum(nums: IntArray, target: Int): IntArray {
val v2i: MutableMap<Int,Int> = mutableMapOf()
for((index, value) in nums.withIndex()) {
val complementary = target-value
if(v2i.contains(complementary)) {
return intArrayOf(v2i[complementary]!!, index)
}
v2i += value to index
}
return intArrayOf()
}
}
JS
1 /** 2 * @param {number[]} nums 3 * @param {number} target 4 * @return {number[]} 5 */ 6 var twoSum = function(nums, target) { 7 const map = new Map(); 8 let res = []; 9 for(let i=0; i<nums.length; ++i) { 10 let oppo = target-nums[i]; 11 if(map.has(oppo)) { 12 res = [map.get(oppo), i]; 13 break; 14 } 15 map.set(nums[i], i); 16 } 17 return res; 18 };
C++
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 using Value = int; 5 using Index = int; 6 unordered_map<Value,Index> hash; 7 for(int i=0; i<nums.size(); ++i) { 8 int value = target-nums[i]; 9 if(hash.count(value)) { 10 return vector<int>{ hash[value], i }; 11 } 12 hash[nums[i]] = i; 13 } 14 15 return {}; 16 } 17 };
以上是关于1. Two Sum的主要内容,如果未能解决你的问题,请参考以下文章