๋ฌธ์ ์ ๋ชฉ | ์ ๋ต๋ฅ | ๋์ด๋ |
1. two-sum | 49.8% | Easy |
Two Sum - LeetCode
Can you solve this real interview question? Two Sum - 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
leetcode.com
๋ฌธ์ ์์ฝ
ํ๊น ์ซ์๊ฐ ์ฃผ์ด์ก์ ๋ ๋ฐฐ์ด ์์์ ํฉ์ผ๋ก ๋ํ๋ผ ์ ์๋ค๋ฉด ์ธ๋ฑ์ค๋ฅผ ๋ฐํํด๋ผ
์กฐ๊ฑด 1) ์ ์ํ ํ๊น ์ซ์์ ์ ์ํ ๋ฐฐ์ด์ด ์ฃผ์ด์ง๋ค
์กฐ๊ฑด 2) ๊ฐ์ ์์๋ฅผ ๋ ๋ฒ ์ฌ์ฉํ๋ ๊ฒ์ ๋ถ๊ฐํ๋ฉฐ ๊ฐ ๋ฌธ์ ์ ์ ํํ ํ๋์ ๋ต์ด ์กด์ฌํ๋ค๊ณ ์๊ฐํด๋ผ
์๊ฐํ๋ ํ์ด 1. Brute-Froce(๋ชจ๋ ๊ฐ๋ฅํ ๊ฒฝ์ฐ๋ฅผ ํ๋์ฉ ๋์ ) -> for ๋ฌธ์ฅ ๋ ๊ฐ ์ฌ์ฉํด์ ๊ตฌํ๊ธฐ - (์๊ฐ๋ณต์ก๋ $O(n^{2})$)
์๊ฐํ๋ ํ์ด 2. ์ ๋ต-์ฒซ๋ฒ์งธ๊ฐ์ด ๋ฆฌ์คํธ์ ์๋์ง ํ์ธ -> for๊ณผ in์ ์ฌ์ฉํด์ ํ์ด - (์๊ฐ๋ณต์ก๋ $O(n^{2})$)
์๊ฐํ๋ ํ์ด 3. ์ ๋ต-์ฒซ๋ฒ์งธ๊ฐ์ ๋ฆฌ์คํธ key ๊ฐ์ ์กฐํ - (์๊ฐ๋ณต์ก๋ $O(n)$)
์๊ฐํ๋ ํ์ด 4. ํฌ ํฌ์ธํฐ ์ด์ฉ -> sort() ํจ์ ์ด์ฉํด์ ์ ๋ ฌํ ๋ค ์ฌ์ฉํ๋ฉด ๋๋ ์ธ๋ฑ์ค๊ฐ ์๋ง์ด ๋๊ธฐ ๋๋ฌธ์ ์ถ์ฒํ์ง ์๋๋ค๊ณ ํจ
ํ์ด 2 (567 ms)
์ ๋ต-์ฒซ ๋ฒ์งธ ๊ฐ์ด ๋ฆฌ์คํธ์ ์๋์ง ํ์ธ
Step1. ์ฒซ๋ฒ์งธ ์์๊ฐ์ ๋บ ๋๋จธ์ง ๊ฐ์ด ๋ฆฌ์คํธ์ ์๋์ง ํ์ธ -> for, in ํจ์
- (์๊ฐ๋ณต์ก๋ $O(n^2)$)
๋ฆฌ์คํธ์ ์ธ๋ฑ์ค์ ๊ฐ์ ๋ชจ๋ ์ ๊ทผํ ์ ์๊ฒ ํ๋ ํจ์ | enumerate(list) |
Setp2. ํด๋น ๊ฐ์ ์ธ๋ฑ์ค ๋ฐํ
๋ฆฌ์คํธ์ ํด๋น ๊ฐ์ด ์๋์ง ํ์ธํ๋ ํจ์ | list.index(value) |
์ค๋ณต๋๋ ์์๋ค์ ์ธ๋ฑ์ค ๋ชจ๋ ์ฐพ๋ ํจ์ | numpy_array=numpy.array(list) numpy.where(numpy_array==๊ฐ)[0] |
๊ตฌํ
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for first_index, first_num in enumerate(nums):
second_num=target-first_num
if(second_num in nums[first_index+1:]):
return [first_index, nums[first_index+1:].index(second_num)+(first_index+1)]
ํ์ด3 (82ms)
์ ๋ต-์ฒซ ๋ฒ์งธ ๊ฐ์ ๋ฆฌ์คํธ key ๊ฐ์ ์กฐํ -> ๋์ ๋๋ฆฌ ์ด์ฉ
Step1. ์ฒซ๋ฒ์งธ ์์๊ฐ์ ๋บ ๋๋จธ์ง ๊ฐ์ด ๋์ ๋๋ฆฌ์ ์๋์ง ํ์ธ -> for, dict[] ํจ์ ์ด์ฉ
- (์๊ฐ๋ณต์ก๋ $O(n)$)
Setp2. ํด๋น ๊ฐ(๋์ ๋๋ฆฌ์ key)์ ์ธ๋ฑ์ค(๋์ ๋๋ฆฌ์ value) ๋ฐํ
๊ตฌํ
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
nums_dict={}
for index, num in enumerate(nums):
nums_dict[num]=index
for first_index, first_num in enumerate(nums):
second_num=target-first_num
if(second_num in nums_dict and first_index!=nums_dict[second_num]):
return [first_index, nums_dict[second_num]]
'์๊ณ ๋ฆฌ์ฆ๐ฅ > ๋ฌธ์ ํ์ด (Python)' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[LeetCode] 15. 3sum (Medium) 2023/5/1 (0) | 2023.05.01 |
---|---|
[python] 2. ์ฝ๋ฉํ ์คํธ์์ ์ฌ์ฉ๋๋ Python ๊ธฐ๋ณธ (0) | 2023.04.30 |
[LeetCode] 5. longest_palindromic_substring (Medium) 2023/4/28 (0) | 2023.04.28 |
[LeetCode] 49. group-anagrams (Medium) 2023/4/28 (0) | 2023.04.28 |
[LeetCode] 937. reorder-data-in-log-files (Easy) 2023/4/27 (0) | 2023.04.27 |