IT/IT 기초(IT기사, 알고리즘, Linux 등)
[leetcode 알고리즘] Two Sum - 난이도 Easy
히유우
2020. 2. 4. 10:05
1. Two Sum - 난이도 Easy
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].
내가 작성한 소스코드:
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]+nums[j]==target){
return new int[] {i, j};
}
}
}
return null;
}
}
Your input | [2,7,11,15] 9 |
---|---|
Output | [0,1] |
Expected | [0,1] |
leetcode's 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[j] == target - nums[i]) {
return new int[] { i, j };
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
솔루션 적용 후 전체 소스코드:
import java.util.Arrays;
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]+nums[j]==target){
return new int[] {i, j};
}
}
}
throw new IllegalArgumentException("No two sum solution");
}
}
public class Algo01 {
public static void main(String[] args){
Solution solution = new Solution();
int[] nums = {2, 7, 11, 15};
int target = 1;
int[] result = solution.twoSum(nums, target);
System.out.println(Arrays.toString(result));
}
}