learning target:
Goal: proficiently use the knowledge learned in Java
Subject content:
The content of this article: Implemented in Java: Squaring an ordered array
Article Directory
Title description:
Give you an integer array nums sorted in non-decreasing order, and return a new array composed of the square of each number, and it is required to also sort 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, the array becomes Is [0,1,9,16,100]
Example 2:
Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]
Problem-solving ideas:
The simpler approach is to square the array first, and then use Arrays.sort() to sort
Implementation code:
class Solution {
public int[] sortedSquares(int[] nums) {
for(int i = 0; i< nums.length; i++){
//进行求平方
nums[i]*= nums[i];
}
Arrays.sort(nums);//排序
return nums;
}
}