文章目录
两数之和
两数之和
【知识点】:HashTable
【思路】:从左向右扫描nums数组,每访问一个数,就看一下target减去这个数在不在map中,如果在的话说明这个数之前有一个数等于target减当前这个数,也就是说,这两数加起来等于target。
【代码】:
public int[] TwoSum(int[] nums, int target)
{
var map = new Dictionary<int, int>();
for (var i = 0; i < nums.Length; i++)
{
if (map.ContainsKey(target - nums[i]))
{
return new int[] {
map[target - nums[i]], i };
}
if (!map.ContainsKey(nums[i]))
{
map.Add(nums[i], i);
}
}
return null;
}
两数之和 II - 输入有序数组
【知识点】:双指针
【思路】:因为是排好序的数组,所以从数组两端向中间走,如果当前l和r指针指向的数的和大于target,r–,小于的话,l++,等于就返回。
public int[] TwoSumII(int[] numbers, int target)
{
int l = 0; int r = numbers.Length - 1;
while (l < r)
{
if (numbers[l] + numbers[r] == target)
{
return new int[] {
l + 1, r + 1 };
}
if (numbers[l] + numbers[r] > target)
{
r--;
}
else
{
l++;
}
}
return null;
}
两数之和 III - 数据结构设计
leetcode题目链接
【思路】:就是把基础版两数之和包成数据结构。
public class TwoSum
{
List<int> nums = new List<int>();
/** Initialize your data structure here. */
public TwoSum() {
}
/** Add the number to an internal data structure.. */
public void Add(int number)
{
nums.Add(number);
}
/** Find if there exists any pair of numbers which sum is equal to the value. */
public bool Find(int target)
{
var map = new Dictionary<int, int>();
for (var i = 0; i < nums.Count; i++)
{
if (map.ContainsKey(target - nums[i]))
{
return true;
}
if (!map.ContainsKey(nums[i]))
{
map.Add(nums[i], i);
}
}
return false;
}
}