티스토리 뷰

PS/leetcode

1. two sum

kingsubin 2021. 8. 17. 10:31
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length - 1; i++) {
            int answer = target - nums[i];
            for (int j = i + 1; j < nums.length; j++) {
                if (answer - nums[j] == 0) {
                    return new int[] {i, j};
                }
            }
        }
        return null;
    }
}
cs

1. 그냥 생각하기 쉽게 푼거 

 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> hashMap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hashMap.containsKey(target - nums[i])) {
                return new int[] {i, hashMap.get(target - nums[i])};
            } else {
                hashMap.put(nums[i], i);
            }
        }
 
        return null;
    }
}
cs

2. 다른 방법 찾아본거

 

HashMap 쓸 생각 못했는데 O(n)이라 훨씬 빠른듯