No1. TwoSum
題目:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
給定一個整數數組,返回這兩個數字的索引,使它們合計成一個特定的目標。
You may assume that each input would have exactly one solution, and you may not use the same element twice.
您可能會認爲每個輸入都只有一個解決方案,並且您可能不會使用相同的元素兩次。
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
思路:
定義兩個索引值 i,j 均代表數組的下標。從左到右依次遍歷整個數組 num[i],num[j]爲任何有可能的兩個數的組合,直到兩數之和等於先前給的target值,返回此時所對應的數組下標。
代碼實現:
public class Solution
{
public int[] TwoSum(int[] nums, int target)
{
for (int i = 0; i < nums.Length; i++)
{
for (int j = i + 1; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
{
return new int[]{i,j};
}
}
}
throw new Exception("error");
}
}