Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 408da5b

Browse files
author
Anish Sachdeva
committed
solves squares of sorted array
1 parent ce15933 commit 408da5b

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

‎README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
|------|:--------:|:----------------------:|
1313
| [Max Consecutive Ones](https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238/) | [![Java](assets/java.png)](java/src/MaxConsecutiveOnes.java) [![Python](assets/python.png)](python/max_consecutive_ones.py) |
1414
| [Find Numbers with Even Number of Digits](https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3237/) | [![Java](assets/java.png)](java/src/FindNumbersWithEvenNumberOfDigits.java) [![Python](assets/python.png)](python/find_number_with_even_number_of_digits.py) |
15-
| [Squares of a Sorted Array](https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3240/) | [![Java](assets/java.png)](java/src/) [![Python](assets/python.png)](python/) |
15+
| [Squares of a Sorted Array](https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3240/) | [![Java](assets/java.png)](java/src/SquaresOfSortedArray.java) [![Python](assets/python.png)](python/squares_of_a_sorted_array.py) |
1616

1717

1818
## Inserting Items Into An Array

‎java/src/SquaresOfSortedArray.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
public class SquaresOfSortedArray {
2+
public int[] sortedSquares(int[] array) {
3+
int[] result = new int[array.length];
4+
int left = 0, right = array.length - 1, k = right;
5+
while (left <= right) {
6+
if (Math.abs(array[left]) < Math.abs(array[right])) {
7+
result[k--] = array[right] * array[right--];
8+
} else {
9+
result[k--] = array[left] * array[left++];
10+
}
11+
}
12+
return result;
13+
}
14+
}

‎python/squares_of_a_sorted_array.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def sortedSquares(self, array: List[int]) -> List[int]:
6+
result = [0] * len(array)
7+
left, right, k = 0, len(array) - 1, len(array) - 1
8+
while left <= right:
9+
if abs(array[left]) > abs(array[right]):
10+
result[k] = array[left] ** 2
11+
left += 1
12+
else:
13+
result[k] = array[right] ** 2
14+
right -= 1
15+
k -= 1
16+
return result

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /