Skip to content

[Tessa1217] WEEK 01 solutions #1129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Apr 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions contains-duplicate/Tessa1217.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import java.util.HashSet;
import java.util.Set;

class Solution {

/** 217. 중복된 수
* 정수 배열 nums가 주어졌을 때 배열 요소 중 한 개 이상이 두 번 이상 중복되어
* 나타는 경우 true를, 모든 배열의 요소가 고유한 경우 false를 반환
*/
public boolean containsDuplicate(int[] nums) {

Set<Integer> distincts = new HashSet<>();

for (int i = 0; i < nums.length; i++) {
distincts.add(nums[i]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

중복을 찾는 것이 목적이므로, 전체 배열을 다 순회하지 않고 중복 발견 즉시 리턴하는 방식은 어떨까요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

`

public boolean containsDuplicate(int[] nums) {

    Set<Integer> distincts = new HashSet<>();

    for (int i = 0; i < nums.length; i++) {
        boolean added = distincts.add(nums[i]);
        if (!added) {
            return true;
        }
    }        

    return false;

}

`

리뷰해주신대로 개선했더니 확실히 런타임이 줄었네요. 좋은 리뷰 감사합니다!

}

return distincts.size() != nums.length;
}
}

25 changes: 25 additions & 0 deletions house-robber/Tessa1217.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
class Solution {

// 전문적인 강도인 당신은 거리에 있는 집들을 털 계획을 세우고 있다.
// 조건: 인접한 집들은 연결된 보안 경비 시스팀이 있어 인접한 집을 같은 날에 털 경우 자동적으로 경찰에 연락이 간다.
// 각 집에 쌓아둔 돈의 양 배열 (정수 배열)이 주어질 때 경찰한테 걸리지 않고 털 수 있는 최대 돈의 양을 반환하시오.
public int rob(int[] nums) {

// 조건: 1 == nums.length (털 집이 한 곳 뿐)
if (nums.length == 1) {
return nums[0];
}

// DP로 계산
nums[1] = Math.max(nums[0], nums[1]);

for (int i = 2; i < nums.length; i++) {
nums[i] = Math.max(nums[i - 1], nums[i - 2] + nums[i]);
}

return nums[nums.length - 1];

}

}

32 changes: 32 additions & 0 deletions longest-consecutive-sequence/Tessa1217.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

/**
* 정렬되지 않은 정수 배열 nums가 주어질 때 가장 긴 연속적인 요소 배열의 길이를 반환
* */
import java.util.Arrays;
public class Solution {

public int longestConsecutive(int[] nums) {

if (nums.length == 0) {
return 0;
}

Arrays.sort(nums);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

문제 제약조건이 시간복잡도 O(n) 까지 허용인데 혹시 통과되셨나요?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

넵 시간복잡도가 정렬 때문에 O(n log n)이 될 것 같기는 한데 일단 문제 풀이 자체는 통과했습니다. 그래도 O(n)으로 시간 복잡도를 줄일 수 있는 풀이를 한번 찾아보는 게 좋겠네요. 좋은 리뷰 감사합니다! 1주차 고생하셨습니다!


int maxCnt = 1;
int cnt = 1;
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == nums[i + 1]) {
continue;
}
if (nums[i] + 1 == nums[i + 1]) {
cnt++;
} else {
cnt = 1;
}
maxCnt = Math.max(maxCnt, cnt);
}
return maxCnt;
}

}
34 changes: 34 additions & 0 deletions top-k-frequent-elements/Tessa1217.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

/**
* 정수 배열 nums와 정수 k가 주어질 때 자주 반복되는 값을 K개 반환
* */
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;

public class Solution {

public int[] topKFrequent(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
}

int[][] arr = map.entrySet().stream()
.map((e) -> new int[]{e.getKey(), e.getValue()})
.toArray(int[][]::new);

Arrays.sort(arr, (f1, f2) -> f2[1] - f1[1]);

int[] frequency = new int[k];
for (int i = 0; i < k; i++) {
frequency[i] = arr[i][0];
}

return frequency;

}

}


50 changes: 50 additions & 0 deletions two-sum/Tessa1217.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import java.util.Map;
import java.util.HashMap;

class Solution {
// 정수 배열 nums와 정수 target가 주어질 때 두 정수의 합이 target이 되는 배열 요소의 인덱스를 반환
// 입력받은 배열에는 하나의 해답만 존재한다고 가정할 수 있으며 같은 요소를 한 번 이상 사용할 수는 없다.
// 반환하는 인덱스의 정렬은 신경쓰지 않아도 된다.

public int[] twoSum(int[] nums, int target) {

// 힌트를 참고하여 시간 복잡도 O(n^2) 이하로 줄이기
// 힌트: Like maybe a hash map to speed up the search?

int[] answer = new int[2];

Map<Integer, Integer> numMap = new HashMap<>();

for (int i = 0; i < nums.length; i++) {
if (numMap.containsKey(target - nums[i])) {
answer[0] = numMap.get(target - nums[i]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

target - nums[i]에 대한 변수를 생성해서 연산한 값을 담아주면 가독성과 연산 최소화가 가능해보입니다!

answer[1] = i;
break;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

배열은 조건 만족 시점에 생성하고 break없이 바로 리턴해도 될것같습니다.

}
numMap.put(nums[i], i);
}

return answer;

}

// public int[] twoSum(int[] nums, int target) {

// // 전체 탐색 진행
// int[] answer = new int[2];

// for (int i = 0; i < nums.length - 1; i++) {
// for (int j = i + 1; j < nums.length; j++) {
// if (nums[i] + nums[j] == target) {
// answer[0] = i;
// answer[1] = j;
// }
// }
// }

// return answer;
// }

}