꼬꼬마 개발자 노트/Coding Problems
Blind 75 Must Do Leetcode - Two sum
Sueeeeee
2022. 6. 7. 17:21
반응형
https://leetcode.com/list/xi4ci4ig/
Favorite - 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
1. Brute Force - O(N^2)
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] result = new int[2];
//1. for문 2개
for(int i =0; i<nums.length-1;i++){
for(int j = i+1;j<nums.length;j++){
if(nums[i]+nums[j] == target) {
result[0] = i;
result[1] = j;
break;
}
}
}
return result;
}
}
2. using hashmap ( O(N) )
class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<>();
for(int i =0; i<nums.length;i++){
if(map.containsKey(nums[i])){
int first = map.get(nums[i]);
return new int[] {first, i};
}else {
map.put(target-nums[i], i);
}
}
return new int[2];
}
}
반응형