The problem is called "Two Sum" with array, so I decided to solve with Python.
Description:
Solution:
When I looked into the each variables, I used nested loop(two for loop) to find out the two variables in the array. And if the sum of two variables equal to the value of target, I return the i and j as a dictionary.
Brute Force:
Time complexity: O(N^2)
Space complexity: O(1)
Solution2:
Using Hash map, you can use only one loop for searching the variables in arrary
Let's say the Target - nums[i] is a nums[x]. nums[x] would be an another interger we should find. Using example 1, the first value of vals is 7. Before putting second value (which is 9 - 7 = 2), 7 is already in the vals. Therefore, the array[0] and array[1] would be the two sum of intergers we tried to find.
* index(nums[i]) return the location of nums[i], so it would be "0" in this case.
Time complexity: O(N)
Space complexity: O(N)
'LeetCode ๐๏ธ > Array' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
152. Maximum Product Subarray (0) | 2023.05.28 |
---|---|
53. Maximum Subarray (0) | 2023.05.27 |
238. Product of Array Except Self (0) | 2023.01.29 |
217. Contains Duplicate (0) | 2023.01.28 |
121. Best Time to Buy and Sell Stock (0) | 2023.01.28 |