首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#版 - LeetCode1 - TwoSum - 题解

C#版 - LeetCode1 - TwoSum - 题解

作者头像
Enjoy233
发布2019-03-05 15:19:03
6650
发布2019-03-05 15:19:03
举报

C#版 - LeetCode1 - TwoSum

1. Two Sum

提交网址: https://leetcode.com/problems/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;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年06月02日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • C#版 - LeetCode1 - TwoSum
    • 1. Two Sum
      • Input
      • Expected answer
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档