Algorithm/LeetCode
-
[array] best time to buy and sell stockAlgorithm/LeetCode 2025. 2. 15. 16:13
✅ Problemhttps://leetcode.com/problems/best-time-to-buy-and-sell-stock/해당 문제는 배열의 값을 그래프로 나열해 시각화 하면 해결 방식 떠올릴 때 도움 됨 ✅ Approach & Solution방식1) 브루트 포스, 시간복잡도 : O(n^2)더보기모든 경우의 수익을 구하게 됨class Solution { public int maxProfit(int[] prices) { int maxProfit = 0; for (int i = 0; i 방식2) 저점과 현재 값과의 차이 계산, 시간복잡도 : O(n)더보기저점과 최대 수익 계산을 for문 안에서 연달아 수행class Solution { public int maxPro..
-
[array] product of array except selfAlgorithm/LeetCode 2025. 2. 8. 17:46
✅ Problemhttps://leetcode.com/problems/product-of-array-except-self/ ✅ Approach & Solution방식1) 시간복잡도 : O(n)더보기자기 자신을 제외하고 자신의 왼쪽 곱셈 결과와 오른쪽 곱셈 결과 곱하기class Solution { public int[] productExceptSelf(int[] nums) { int[] result = new int[nums.length]; // 자기 자신의 왼쪽 곱셈 결과 포함시키기 int p = 1; // 자기 자신은 제외시켜야 하므로 1로 초기화 for (int i = 0; i = 0; i--) { result[i] *= p;..
-
[array] 3sumAlgorithm/LeetCode 2025. 2. 1. 15:01
✅ Problemhttps://leetcode.com/problems/3sum/description/ ✅ Approach & Solution방식) 정렬 후 투 포인터 사용더보기3개를 찾아야 할 때 : 1개는 고정해두고 나머지 2개를 찾자나머지 2개 찾을 때 투 포인터 사용정렬 필수 (배열의 인덱스 값 활용하지 않기 때문에 정렬 가능)class Solution { public List> threeSum(int[] nums) { int left, right, sum; List> results = new ArrayList(); Arrays.sort(nums); for (int i = 0; i 0 && nums[i] == nums[i-1]) { ..
-
[array] trapping rain waterAlgorithm/LeetCode 2025. 1. 26. 15:50
✅ Problemhttps://leetcode.com/problems/trapping-rain-water/description/ ✅ Approach & Solution조건물이 고이려면 양 쪽이 막혀있어야 한다.양 쪽 높이 중 더 낮은 높이까지만 물이 고일 수 있다. 방식1) 투 포인터 사용더보기배열이 주어졌을 때 O(N) 시간복잡도로 구현하려면 투 포인터 방식 사용배열의 양 끝에서 시작, left class Solution { public int trap(int[] height) { int volume = 0; int left = 0; int right = height.length - 1; int leftMax = height[left]; ..