์๊ณ ๋ฆฌ์ฆ/LeetCode
[LeetCode] 001. Two Sum JAVA
Bhinney
2022. 12. 15. 11:47
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
๐ ๋ฌธ์
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
๐ ๋ฐฉ๋ฒ 1. ๋ฐ๋ณต๋ฌธ์ ์ด์ฉํ ํ์ด
- ๋ฐฐ์ด์ ๊ธธ์ด๋งํผ ๋ฐ๋ณต๋ฌธ์ ์ด์ฉ
- ๋ํ ๋ ์๊ฐ target๊ณผ ์ผ์นํ๋์ง ํ์ธ
- ๋ง๋ค ์ ์์ผ๋ฉด ๋น ๋ฐฐ์ด์ ๋ฆฌํด
- ์ด์ค ๋ฐ๋ณต๋ฌธ์ผ๋ก ์๊ฐ ๋ณต์ก๋ : O(n²)
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length -1 ; i++ ) {
for(int j = i+1; j < nums.length; j++) {
if (nums[i] + nums[j] == target) {
return new int[]{i,j};
}
}
}
return new int[]{};
}
}
๐ ๋ฐฉ๋ฒ 2. Map์ ์ด์ฉํ ํ์ด
- ํ์ฌ Index๋ฅผ value, ํด๋น ๋ณด์ ๊ฐ์ key
- ๋ณด์ : ๋ณด์ถฉ์ ํด์ฃผ๋ ์
- ๋ฐ๋ณต๋ฌธ์ ๋๋ฉฐ ํ์ฌ ์์ ๋ณด์๊ฐ ์๋์ง ํ์ธ
- ๋ง๋ค ์ ์์ผ๋ฉด ๋น ๋ฐฐ์ด์ ๋ฆฌํด
- ์๊ฐ ๋ณต์ก๋ : O(n)
import java.util.HashMap;
import java.util.Map;
class Solution {
public int[] twoSum(int[] nums, int target) {
/* Map์ ์ด์ฉํ์ฌ ๊ตฌํ */
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(nums[i])){
return new int[]{map.get(nums[i]), i};
}
map.put(target - nums[i], i);
}
/* ์์ ๊ฒฝ์ฐ, ๋น ๋ฐฐ์ด ๋ฆฌํด */
return new int[]{};
}
}