티스토리 뷰
Leetcode - Two sum problems has several approaches. first one is O(n^2) time complexity with two for loops. I'll not cover that approach in this post.
1 O(n log\_n)
approach
1 sorting arrays. remind that origin index should be remained.
2 using two pointers, if sum value is same with target value then return it.
3 if sum value is larger than target value, then decrease tail pointer. If in opposite situation, then increase head pointer.
following code is written in JavaScript
const twoSum = (nums, target) => {
const nums_with_idx = [...nums].map((i, idx) => [i, idx]);
const sorted = nums_with_idx.sort((a, b) => a[0] - b[0]);
let i = 0;
let j = sorted.length - 1;
while (i < j) {
const sum = sorted[i][0] + sorted[j][0];
if (sum == target) return [sorted[i][1], sorted[j][1]];
if (sum > target) j--;
else i++;
}
return [];
};
2 O(n) ~ O(n log n)
approach
1 While iterating arrays, find matching element that makes sum with current value equals target value.
2 If couldn't find matched element, then assign item in dictionary(hash) with index.
Notice. time complexity is depends on implementation of hash data structure. O(n) ~ O(n log n)/remind c++ has Map that consume O( log n ) in a operation - STL Map based on Red black tree
following code is written in Python
class Solution(object):
def twoSum(self, nums, target):
d:dict = {}
res = None
for i in range(0, len(nums)):
cur = nums[i]
if d.get(target - cur) is not None: res = [d[target-cur], i]
d[cur] = i
if res: break
return res
Thanke you.
'알고리즘 문제 > sort, search' 카테고리의 다른 글
codeforces 283 div2 d tennis game (0) | 2019.11.02 |
---|---|
CF 1041D Glider (0) | 2018.09.20 |
888E : Maximum Subsequence (0) | 2017.11.12 |
Codeforces : Ordering Pizza (0) | 2017.10.02 |
- Total
- Today
- Yesterday
- 로젠
- Grafana
- 이산수학
- 엄청난 인내심과 시뮬레이션을 위한 아레나 툴
- 자바스크립트
- rosen
- 최단경로 알고리즘
- 데이터 중심 애플리케이션 설계
- Discrete Mathematics
- paul wilton
- 백준
- 항해99
- 이산 수학
- Arena
- grafana cloud
- 아레나 시뮬레이션
- Simulation
- flutter
- beginning javascript
- javascript
- 자바스크립트 예제
- 아레나시뮬레이션
- 대규모 시스템 설계 기초
- 아레나
- 명제논리
- 그라파나
- arena simulation
- Propositional and Predicate Logic
- 가상 면접 사례로 배우는 대규모 시스템 설계 기초
- 시뮬레이션
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |