c# 字典 ContainsKey 方法

public int[] TwoSum(int[] nums, int target) {
         Dictionary<int, int> kvs = new Dictionary<int, int>();
        for (int i = 0; i < nums.Length; i++)
        {
            int complement = target - nums[i];
            if (kvs.ContainsKey(complement) && kvs[complement] != i)
            {
                return new int[] {  kvs[complement] ,i};
            }
            //需要对重复值进行判断,若结果包含了重复值,则已经被上面给return了;所以此处对于重复值直接忽略
            if (!kvs.ContainsKey(nums[i]))
            {
                kvs.Add(nums[i], i);
            }
        }
        return new int[] { 0, 0 };
    }
}

力扣解题

posted @ 2020-06-19 12:31  唯爱金生  阅读(5333)  评论(0编辑  收藏  举报