Skip to content

Commit d4439f8

Browse files
committed
Merge remote-tracking branch 'upstream/main'
2 parents a3b4539 + 0778811 commit d4439f8

38 files changed

+1348
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# 시간복잡도: O(N)
2+
# 공간복잡도: O(N)
3+
class Solution:
4+
def longestConsecutive(self, nums: List[int]) -> int:
5+
nums = set(nums)
6+
answer = 0
7+
8+
for num in nums:
9+
if num - 1 not in nums:
10+
length = 1
11+
12+
while num + length in nums:
13+
length += 1
14+
15+
answer = max(answer, length)
16+
17+
return answer
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* https://leetcode.com/problems/longest-consecutive-sequence/
3+
* T.C.: O(n)
4+
* S.C.: O(n)
5+
*/
6+
function longestConsecutive(nums: number[]): number {
7+
const numSet = new Set(nums);
8+
let max = 0;
9+
10+
for (const num of numSet) {
11+
if (numSet.has(num - 1)) {
12+
continue;
13+
}
14+
15+
let count = 0;
16+
while (numSet.has(num + count)) {
17+
count++;
18+
}
19+
20+
if (count > max) max = count;
21+
}
22+
23+
return max;
24+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* https://leetcode.com/problems/longest-consecutive-sequence
3+
* time complexity : O(n)
4+
* space complexity : O(n)
5+
*/
6+
const findStreak = (set: Set<number>) => (num: number): number => {
7+
if (!set.has(num - 1)) return takeWhile(num, currentNum => set.has(currentNum)).length;
8+
return 0;
9+
};
10+
11+
const takeWhile = (start: number, predicate: (value: number) => boolean): number[] => {
12+
const result: number[] = [];
13+
let currentNum = start;
14+
while (predicate(currentNum)) {
15+
result.push(currentNum);
16+
currentNum += 1;
17+
}
18+
return result;
19+
}
20+
21+
const max = (maxStreak: number, currentStreak: number): number => Math.max(maxStreak, currentStreak);
22+
23+
function longestConsecutive(nums: number[]): number {
24+
const numSet = new Set(nums);
25+
26+
return [...numSet]
27+
.map(findStreak(numSet))
28+
.reduce(max, 0);
29+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//time-complexity : O(n)
2+
//space-complexity : O(n)
3+
4+
const longestConsecutive = function (nums) {
5+
let longest = 0;
6+
const set = new Set(nums);
7+
8+
while (set.size > 0) {
9+
let count = 0;
10+
const originalSeed = set.values().next().value; //set의 첫 번째 원소 get
11+
12+
seed = originalSeed;
13+
14+
while (set.has(seed)) {
15+
set.delete(seed);
16+
count++;
17+
seed += 1;
18+
}
19+
20+
seed = originalSeed - 1;
21+
22+
while (set.has(seed)) {
23+
set.delete(seed);
24+
count++;
25+
seed -= 1;
26+
}
27+
28+
if (count > longest) longest = count;
29+
}
30+
31+
return longest;
32+
};
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
class SolutionLongestConsecutiveSequence {
5+
6+
public int longestConsecutive(int[] nums) {
7+
// 정렬되지 않은 정수 nums 배열이 주어지면 가장 긴 연속 요소 시퀀스 길이를 반환
8+
// O(N) 시간 내 실행되야함
9+
// 전부 해시맵에 때려넣고, 키를 꺼내 연속 요소가 있는지 확인한다
10+
// 연속 요소가 있으면 answer를 1 증가시키고, 연속 요소는 제거한다
11+
// 시간복잡도: O(N), 공간복잡도: O(N)
12+
13+
Set<Integer> set = new HashSet<>();
14+
for (var num : nums) {
15+
set.add(num);
16+
}
17+
var answer = 0;
18+
for (var num : nums) {
19+
var length = 1;
20+
21+
if (set.contains(num-1)) {
22+
set.remove(num);
23+
var minusKey = num;
24+
while (set.contains(--minusKey)) {
25+
length++;
26+
set.remove(minusKey);
27+
}
28+
}
29+
30+
if (set.contains(num+1)) {
31+
set.remove(num);
32+
var plusKey = num;
33+
while (set.contains(++plusKey)) {
34+
length++;
35+
set.remove(plusKey);
36+
}
37+
}
38+
39+
if (length > answer) {
40+
answer = length;
41+
}
42+
}
43+
44+
return answer;
45+
}
46+
}
Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package leetcode_study
2+
3+
import io.kotest.matchers.shouldBe
4+
import org.junit.jupiter.api.Test
5+
import kotlin.math.max
6+
7+
class `longest-consecutive-sequence` {
8+
fun longestConsecutive(nums: IntArray): Int {
9+
if (nums.isEmpty()) return 0
10+
return usingUnionFind(nums)
11+
}
12+
13+
/**
14+
* 1. 배열을 정렬하여 순서대로 순회하며 연속 수열 길이를 확인한다.
15+
* TC: O(n * log(n)), SC: O(1)
16+
*/
17+
private fun usingSort(nums: IntArray): Int {
18+
nums.sort()
19+
20+
var (length, maxLength) = 1 to 0
21+
for (index in 0 until nums.size - 1) {
22+
if (nums[index] == nums[index + 1]) {
23+
continue
24+
} else if (nums[index] + 1 == nums[index + 1]) {
25+
length++
26+
} else {
27+
maxLength = max(length, maxLength)
28+
length = 1
29+
}
30+
}
31+
return max(length, maxLength)
32+
}
33+
34+
/**
35+
* 2. Set의 자료구조를 활용하여 가장 작은 값부터 while문을 통한 최대 증가 값을 반환한다.
36+
* TC: O(n), SC: O(n)
37+
*/
38+
private fun usingSet(nums: IntArray): Int {
39+
val numberSet = nums.toSet()
40+
var maxLength = 0
41+
42+
for (number in nums) {
43+
if (numberSet.contains(number - 1)) {
44+
continue
45+
}
46+
var length = 1
47+
while (numberSet.contains(number + length)) {
48+
length++
49+
}
50+
maxLength = max(maxLength, length)
51+
}
52+
53+
return maxLength
54+
}
55+
56+
/**
57+
* 3. Union-Find
58+
* TC: O(n), SC: O(n)
59+
*/
60+
private fun usingUnionFind(nums: IntArray): Int {
61+
val nodes = mutableMapOf<Int, Int>()
62+
val dsu = DSU(nums.size)
63+
64+
for ((i,n) in nums.withIndex()) {
65+
if (n in nodes) continue
66+
67+
nodes[n - 1]?.let { dsu.union(i, it) }
68+
nodes[n + 1]?.let { dsu.union(i, it) }
69+
70+
nodes[n] = i
71+
}
72+
73+
return dsu.maxLength()
74+
}
75+
76+
@Test
77+
fun `입력받은 정수 배열의 최대 연속 수열 길이를 반환한다`() {
78+
longestConsecutive(intArrayOf()) shouldBe 0
79+
longestConsecutive(intArrayOf(100,4,200,1,3,2)) shouldBe 4
80+
longestConsecutive(intArrayOf(11,23,12,13,14,21)) shouldBe 4
81+
longestConsecutive(intArrayOf(0,3,7,2,5,8,4,6,0,1)) shouldBe 9
82+
longestConsecutive(intArrayOf(11,64,43,12,13,10,9,8,7)) shouldBe 7
83+
}
84+
}
85+
86+
class DSU(val n: Int) {
87+
private val parent = IntArray(n) { it }
88+
private val size = IntArray(n) { 1 }
89+
90+
private fun find(x: Int): Int {
91+
if (parent[x] != x)
92+
parent[x] = find(parent[x])
93+
return parent[x]
94+
}
95+
96+
fun union(x: Int, y: Int) {
97+
val root = find(x)
98+
val child = find(y)
99+
if(root != child) {
100+
parent[child] = root
101+
size[root] += size[child]
102+
}
103+
}
104+
105+
fun maxLength(): Int {
106+
var res = 0
107+
for (i in parent.indices) {
108+
if (parent[i] == i)
109+
res = maxOf(res, size[i])
110+
}
111+
return res
112+
}
113+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
var longestConsecutive = function (nums) { // sorting approach
2+
if (!nums.length) return 0;
3+
let set = new Set(nums);
4+
let sorted = [...set].sort((a, b) => a - b);
5+
let longestSeq = 0;
6+
let currSeq = 1;
7+
8+
for (let i = 1; i < sorted.length; i++) { // loop through sorted list to find sequence
9+
if (sorted[i - 1] + 1 === sorted[i]) {
10+
currSeq++;
11+
} else {
12+
longestSeq = Math.max(longestSeq, currSeq); // compare sequence to figure out the longest
13+
currSeq = 1;
14+
}
15+
}
16+
17+
return Math.max(longestSeq, currSeq);
18+
};
19+
20+
// time - O(nlong) using sort
21+
// space - O(n) store nums in set
22+
23+
24+
// TODO - try O(n) TC approach
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* https://leetcode.com/problems/maximum-product-subarray
3+
* T.C. O(n)
4+
* S.C. O(1)
5+
* All numbers are integers, so multiplying two numbers cannot result in a smaller absolute value.
6+
* It's important to pay attention to zeros and negative numbers.
7+
*/
8+
function maxProduct(nums: number[]): number {
9+
if (nums.length === 0) return 0;
10+
11+
let max = nums[0];
12+
let min = nums[0];
13+
let result = nums[0];
14+
15+
for (let i = 1; i < nums.length; i++) {
16+
const num = nums[i];
17+
if (num < 0) [max, min] = [min, max];
18+
19+
max = Math.max(num, max * num);
20+
min = Math.min(num, min * num);
21+
22+
result = Math.max(result, max);
23+
}
24+
25+
return result;
26+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* https://leetcode.com/problems/maximum-product-subarray
3+
* time complexity : O(n)
4+
* space complexity : O(1)
5+
*/
6+
function maxProduct(nums: number[]): number {
7+
let r = nums[0];
8+
let mx = 1, mn = 1;
9+
10+
for (let i = 0; i < nums.length; i++) {
11+
const tempMx = mx * nums[i];
12+
const tempMn = mn * nums[i];
13+
14+
mx = Math.max(tempMx, tempMn, nums[i]);
15+
mn = Math.min(tempMx, tempMn, nums[i]);
16+
17+
r = Math.max(r, mx);
18+
}
19+
20+
return r;
21+
}

0 commit comments

Comments
 (0)