1. Two Sum

Posted blackyao

tags:

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

Kotlin code:

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()
    }
}

 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的主要内容,如果未能解决你的问题,请参考以下文章

1_Two Sum --LeetCode

Two Sum

每日一算法之two sum

LeetCode之371. Sum of Two Integers

Two Sum

1. Two Sum