## DEV Community ๐ฉโ๐ป๐จโ๐ป

FakeStandard

Posted on • Updated on

# Two Sum

#1.Two Sum

### Problem statement

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

### Explanation

ๅพ็ตฆๅฎ็ `array` ไธญๆพๅฐๅฉๅๆธ็ธๅ ็ญๆผ `target`๏ผไธฆไธ่ฟๅๅฉๆธ็ดขๅผ

• ๅชๆๆไธๅๆๆ็ญๆก
• ๅไธๅๅ็ด ไธๆไฝฟ็จๅฉๆฌก
• ๅฏไปฅ่ฟๅไปปไฝ้ ๅบ็็ดขๅผ

### Solution

ๆฏ่ผ็ด่ฆบๅฐๆนๅผๆฏไฝฟ็จ้่ฟดๅ่ฟญไปฃ้ฃๅไพ่งฃ๏ผ้็จฎๆดๅ่งฃๆณ้ๅฐ่ณๆ้่ผๅคงๆ๏ผ้่ฆๆดๅคๆ้ไพๅฎๆใ

ๅฆๆไปฅๆ้่ค้ๅบฆไฝ็บ่้๏ผ้่จญๆณๆธๅฐ่ฟดๅ็ไฝฟ็จๆฌกๆธ๏ผ่ฎๅท่กๆ้ๅคงๅนไธ้๏ผ้ฃ้บผๅฏไฝฟ็จไธๅ้กๅค็ฉบ้ไพๅฒๅญๅ็ด ๏ผไปฅ้ๅฐ็ฉบ้ๆๆ้็ๆณๆณ๏ผ้็ถๆญคๆนๆณ่ฎๆ้่ค้ๅบฆ้ไฝ๏ผๅๆไนๆ้ซไบ็ฉบ้่ค้ๅบฆใ

Array
้้้่ฟดๅ้ไธ่ตฐ่จช้ฃๅ๏ผๅ ็บๅ็ด ไธๅฏ้่ค๏ผๆๅ i+1 ็ฅ้่ชๅทฑไปฅๅ่จ็ฎ้็ๅผ

``````public int[] TwoSum(int[] nums, int target)
{
int i, j;

for (i = 0; i < nums.Length; i++)
for (j = i + 1; j < nums.Length; j++)
if (nums[i] + nums[j] == target)
return new int[] { i, j };

return null;
}
``````

HashTable
ไฝฟ็จไธๅ้กๅค็ฉบ้ `HashTable`๏ผไปฅ้ๅฐ็จ็ฉบ้ๆๅๆ้

``````public int[] TwoSum(int[] nums, int target)
{
Hashtable hash = new Hashtable();

for (int i = 0; i < nums.Length; i++)
{
int num = nums[i];
int diff = target - num;

if (hash.ContainsKey(diff))
return new int[] { i, (int)hash[diff] };

if (!hash.ContainsKey(num))
}

return null;
}
``````

Dictionary
ไธๆจฃไฝฟ็จไธๅ้กๅค็ฉบ้ `Dictionary` ้ๅฐ็ฉบ้ๆๆ้็็ฎ็

``````public int[] TwoSum(int[] nums, int target)
{
Dictionary<int, int> dic = new Dictionary<int, int>();

for (int i = 0; i < nums.Length; i++)
{
int num = nums[i];
int diff = target - num;

if (dic.ContainsKey(diff))
return new int[] { i, (int)dic[diff] };

if (!dic.ContainsKey(num))
}

return null;
}
``````

### Reference

LeetCode Solution

GitHub Repository

Thanks for reading the article ๐ท ๐ป ๐ผ

If you like it, please don't hesitate to click heart button โค๏ธ
or click like on my Leetcode solution