Wednesday, March 30, 2022

Leet Code 977. Squares of a Sorted Array

https://leetcode.com/problems/squares-of-a-sorted-array/


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].




package pep.Day52;

public class LeetCode_977_Squares_of_sorted_array {
public static void main(String[] args) {
int[] x = sortedSquares(new int[]{-4, -1, 0, 3, 10});

for (int xx : x)
System.out.print(xx + " ");
}

public static int[] sortedSquares(int[] nums) {
int start = 0, end = nums.length - 1, answer_idx = end;
int[] ans = new int[nums.length];

while (answer_idx >= 0) {
if (square(nums[start]) >= square(nums[end]))
ans[answer_idx--] = square(nums[start++]);
else
ans[answer_idx--] = square(nums[end--]);
}

return ans;
}

private static int square(int num) {
return num * num;
}
}


public static int[] sortedSquares(int[] nums) {
int[] ans = new int[nums.length];
int i = 0;
int j = nums.length-1;
int k= nums.length-1;
while (i <= j) {
int left = nums[i] * nums[i];
int right = nums[j] * nums[j];

if (left > right) {
ans[k--] = left;
i++;
} else {
ans[k--] = right;
j--;
}
}

return ans;
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...