执行用时:512 ms, 在所有 C# 提交中击败了35.05%的用户
内存消耗:31.2 MB, 在所有 C# 提交中击败了6.82%的用户
思路:首先对目标数组进行遍历,如果当前值nums[i]>target,跳过,若nums[i]<target,则在余下数组里面遍历是否有target - nums[i]。若有,将两数赋给结果数组,之后返回结果数组。
public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] result = new int[2];
bool flag = true;
Dictionary<int, int> tempDic = new Dictionary<int, int>();
//进行对于字典的写入,字典的每一个键代表index,每个值代表nums中index位置的数
for (int i = 0; i < nums.Length; i++)
{
tempDic.Add(i,nums[i]);
}
for (int i = 0; i < nums.Length; i++)
{
if (target < nums[i])
{
flag = false;
}
if (target == nums[i]*2)
{
result[0] = i;
for (int j = i+1; j < nums.Length; j++)
{
if (nums[j] == nums[i])
{
result[1] = j;
return result;
}
}
}
else
{
result[0] = i;
for (int j = i; j < nums.Length; j++)
{
if ((nums[i] + nums[j]) == target)
{
result[1] = j;
return result;
}
}
}
}
return null;
}
}