[Leetcode学习-c++&java]squares-of-a-sorted-array

问题

难度:easy

说明:

水题,把已经从小到大排序好的数组元素进行平方,然后再返回一个从小到大的数组,因为有负数,平方之后再排序也简单。

题目连接:https://leetcode.com/problems/squares-of-a-sorted-array/

输入范围:

  • 1 <= nums.length <= 104
  • -104 <= nums[i] <= 104
  • nums is 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]

我的代码:

用api就非常简单,也可以自己写个

java:

class Solution {
    public int[] sortedSquares(int[] A) {
        for(int i = 0;i < A.length;i ++) A[i] = (int)Math.pow(A[i], 2);
        Arrays.sort(A);
        return A;
    }
}
class Solution {
    public int[] sortedSquares(int[] A) {
        int len = A.length, left = 1, right, index = 0;
        int[] B = new int[len];
        for(int i = 0;i < len;i ++) A[i] = (int)Math.pow(A[i], 2);
        for(;left < len; left ++) 
            if(A[left - 1] < A[left]) break;
        left --;
        right = left + 1;
        while(right < len && left >= 0) {
            if(A[left] < A[right]) B[index ++] = A[left --];
            else if(A[left] > A[right]) B[index ++] = A[right ++];
            else B[index ++] = B[index ++] = A[left --] = A[right ++];
        }
        while(left >= 0) B[index ++] = A[left --];
        while(right < len) B[index ++] = A[right ++];
        
        return B;
    }
}

c++:

class Solution {
public:
	vector<int> sortedSquares(vector<int>& nums) {
		int len = nums.size(), left = 1, index = 0;
		vector<int> res(len);
		for (int i = 0; i < nums.size(); i++) nums[i] = pow(nums[i], 2);
		for (; left < nums.size(); left++)
			if (nums[left - 1] < nums[left]) break;
		left = left - 1;
		int right = left + 1;
		while (right < len && left >= 0) {
			if (nums[right] > nums[left]) res[index ++] = nums[left--];
			else if (nums[right] < nums[left]) res[index ++] = nums[right++];
			else res[index ++] = res[index ++] = nums[left--] = nums[right++];

		}
		while (left >= 0) res[index ++] = nums[left--];
		while(right < len) res[index ++] = nums[right++];
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/qq_28033719/article/details/111225572
今日推荐