力扣练习题1
两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
c#语言代码:
遍历整个数组,用双循环的方法找出需要的两个值,时间复杂度为O(n^2)
public class Solution {
public int[] TwoSum(int[] nums, int target) {
for(i=0;i<nums.length;i++)
{
for(j=0;j<nums.length;j++)
{
if(nums[i]==target-nums[j])
return new.int[]{i,j};
}
}
}
或者采用字典,在第一次遍历的过程中我们把数据按字典的方式存下来,下一个遍历过程中直接用差值(目标-当前遍历的值)去字典中查询,如果有结果则直接返回结果。
public int[] TwoSum2(int[] nums, int target)
{
int[] result = new int[2];
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; i++)
{
int complement = target - nums[i];
if (dict.ContainsKey(complement))
{
result[0] = dict[complement];
result[1] = i;
return result;
}
else
{
dict[nums[i]] = i;
}
}
return null;
}