Java
JavaMister-Hopeliznculmy
Mister-Hope
/*
* Runtime: 10 ms, faster than 41.97% of Java online submissions for Two Sum.
*
* Memory Usage: 56.5 MB, less than 6.02% of Java online submissions for Two Sum.
*/
import java.util.HashMap;
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int j = target - nums[i];
if (map.containsKey(j))
return new int[] {map.get(j), i};
map.put(nums[i], i);
}
throw new IllegalArgumentException("No solution");
}
}
lizncu
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 IllegalArgumentException("No two sum solution");
}
}
lmy
class Solution {
public int[] twoSum(int[] nums, int target) {
int n = nums.length;
for (int i = 0; i < n; ++i) {
for (int j = i + 1; j < n; ++j) {
if (nums[i] + nums[j] == target) {
return new int[] {i, j};
}
}
}
return new int[0];
}
}