Leetcode Answers 1

开始我的Leetcode刷题记答案系列,基本上是按照序号来,先写答案,后考虑Optimization。这是第一篇,Frequency为绿的Two Sum。题目上给的tag有HashTable,然而说实话我觉得不用,两个for loop嵌套然后避开同一个element就好了。

题目:
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:

1
2
3
4
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

Answer:

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
public int[] TwoSum(int[] nums, int target) {
for(int i=0;i<nums.Length;i++){
for(int j=0;j<nums.Length;j++){
if((nums[i] == (target - nums[j]))&&i!=j){
return new int[]{i, j};
}
}
}
return new int[]{};
}
}

简单明了,没啥可说的。

17-03-08
@Sturbridge