문제링크 - https://leetcode.com/problems/two-sum/
브루트 포스를 사용하여 목표값과 같으면 반환하여 해당 문제를 쉽게 해결할 수 있다.
데이터 선언이 필요 없이 해당 배열을 탐색하여 가져온 값으로 문제를 해결할 수 있다.
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};
}
}
}
return new int[] {};
}
}
시간 복잡도
공간 복잡도
다음과 같은 점수를 기록했다.
이중 반복문은 해당 코드를 쉽게 구현할 수 있지만 시간 복잡도에서 상당히 비효율적이다.
시간 복잡도를 개선하기 위한 방법은 다음과 같다.
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> hashMap = new HashMap<>();
for(int i = 0 ; i<nums.length;i++){
int result = target-nums[i];
if(hashMap.containsKey(result)){
return new int[]{hashMap.get(result),i};
}
hashMap.put(nums[i],i);
}
return new int[] {};
}
}