코딩테스트

[LeetCode] 1. Two Sum

728x90

leetcode.com/problems/two-sum/

 

Two Sum - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

오늘 문제는 8분만에 풀었다📚 익숙한 for문으로 해결할 수 있는 문제여서 가능했다.

 

1. Two Sum

return indices of the two numbers such that they add up to target.
➡ 배열안의 값 두 개를 더해서 target이 되는 배열 인덱스를 배열형태로 return
Only one valid answer exists.

➡ 더해서 유효한 정답이 되는 경우는 한 가지 뿐!

 

중첩 for문을 써서 해결했다.

유효한 정답이 되는 경우가 한 가지 뿐이므로 기존에 더했던 값은 다시 연산하지 않아도 된다. 따라서, j 값은 i+1 부터 시작한다.

 

예)

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

2+7 2+11 2+15

7+11 7+15

11+15

 

풀이

public class TwoSum0316 {
	public int[] twoSum(int[] nums, int target) {
		int [] twoSum = new int[2];
		
		for(int i=0;i<nums.length;i++) {
			//이미 더한 경우는 더하지 않아도 되므로 j=i+1
			for(int j=i+1;j<nums.length;j++) {
				if(nums[i]+nums[j]==target) {
					twoSum[0] = i;
					twoSum[1] = j;
					return twoSum;
				}
			}
		}
		
		return twoSum;
	}
}

 

값을 찾은 경우 바로 return 해서 런타임을 줄였다.

  • break; return; 어떤 것도 쓰지 않았을 때 Runtime : 9 ms
  • break; 사용 Runtime : 8 ms
  • return; 사용 Runtime : 0 ms

728x90