LeetCode 20221206 #1 (1. Two Sum; Easy)

题目连结: 1. Two Sum; Easy

题目说明:

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.

Example 1:
Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:
Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:
Input: nums = [3,3], target = 6
Output: [0,1]

解答:

public class Solution {    public int[] TwoSum(int[] nums, int target) {        Dictionary<int, int> temp = new Dictionary<int, int>();        for (int i = 0; i < nums.Length; i++)        {            int left = target - nums[i]; //目前数字的余数            if (temp.ContainsKey(left))                return new int[] { temp[left], i  }; //找到了,直接回传Index            if (!temp.ContainsKey(nums[i]))                temp.Add(nums[i], i); //没有找到,把找过的存起来,可以当作另一个数字的余数        }        return null;    }}

解题心得:

最近手边专案到一段落,趁着空档锻鍊一下自己的思考逻辑,也把C#各种资料结构、工具更加熟悉,并记录解题过程。
利用余数,寻访每个数字,并使用Dictionary的Key/Value把出现过的数字存在Dictionary,重点是将数字存在Dictionary.Key,数字的index存在Dictionary.Value,再利用Dictionary.ContainsKey找到相对应的余数,并回传Dictionary.Value(Index)。

参考:

参考:透过 LeetCode 解救美少女工程师的演算法人生系列 第 3 篇


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章