일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Jetpack Compose
- 백준알고리즘
- 전이
- leetcode
- MYSQL
- 맛집
- 폐CT
- android auto
- 동위원소치료
- java
- Android
- 림프절전이
- 객체
- 갑상선암
- 정렬 알고리즘
- 방사성 동위원소 치료
- 카페
- 경력 개발자
- 알고리즘
- 임파선전이
- 갑상선암용인세브란스
- firebase
- 방사성동위원소치료
- 안드로이드
- Compose
- Android Compose
- 저요오드식
- 프로그래머스
- 입원
- 수술
Archives
- Today
- Total
새우버거의 개발 블로그
[Java] LeetCode 977 : Squares of a Sorted Array 본문
LeetCode # 977
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation:
After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Constraints:
- 1 <= nums.length <= 104
- -104 <= nums[i] <= 104
- nums is sorted in non-decreasing order.
Solution #1
class Solution {
public int[] sortedSquares(int[] nums) {
int[] s = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
s[i] = nums[i] * nums[i];
}
Arrays.sort(s);
return s;
}
}
Result #1
💡 간단하게 Arrays.sort()를 구현하여 문제를 풀었다. 하지만 Arrays.sort()의 시간 복잡도는 O(n log n).
Solution #2 (1ms)
class Solution {
public int[] sortedSquares(int[] nums) {
int[] result = new int[nums.length];
int left = 0, right = nums.length-1;
for (int i = nums.length-1; i >=0; i--) {
if(Math.abs(nums[left])>Math.abs(nums[right])){
result[i] = nums[left] * nums[left];
left++;
}
else{
result[i] = nums[right] * nums[right];
right--;
}
}
return result;
}
}
Result #2
💡 left, right 인덱스를 증감시켜 절댓값 비교를 하는 방법으로 풀었다. 1ms로 시간이 감소한 결과를 볼 수 있다.
More Algorithm!
👇👇
github.com/ggujangi/ggu.leet-code
ggujangi/ggu.leet-code
LeetCode, Java. Contribute to ggujangi/ggu.leet-code development by creating an account on GitHub.
github.com
출처 : leetCode
'알고리즘 > LeetCode' 카테고리의 다른 글
[Java] LeetCode 914 : X of a Kind in a Deck of Cards (0) | 2021.04.17 |
---|---|
[Java] LeetCode 1486 : XOR Operation in an Array (0) | 2021.04.17 |
[Java] LeetCode 1295 : Find Numbers with Even Number of Digits (0) | 2021.03.30 |
[Java] LeetCode 485 : Max Consecutive Ones (0) | 2021.03.30 |
[JAVA] LeetCode Explore - May Week 1 : First Bad Version (0) | 2020.05.03 |