C#版 - LeetCode1 - TwoSum

C#版 - LeetCode1 - TwoSum

1. Two Sum


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].

Case 2:

Input
[2,3,11,3]
6
Expected answer
[1,3]

思路:
使用Dictionary<int, int>存储每一个整数在原输入中的下标,返回结果中下标从0开始算,需从小到大排列。特别要注意的是有相等数字的情形~

已AC代码:

public class Solution
{
    public int[] TwoSum(int[] nums, int target)
    {
        int[] res = {0, 0};
        int len = nums.Length;
        Dictionary<int, int> dict = new Dictionary<int, int>();
        for (int i = 0; i < len; i++)
        {
            int query = target - nums[i];
            if (dict.ContainsKey(query))
            {
                int min = (i <= dict[query]) ? i : dict[query];
                int max = (i <= dict[query]) ? dict[query] : i;
                return new int[] { min, max };
            }
            else if (!dict.ContainsKey(nums[i]))
            {
                dict.Add(nums[i], i);
            }
        }

        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/yanglr2010/article/details/80551669