首页 > 其他分享 >数组:有序数组的平方

数组:有序数组的平方

时间:2022-09-05 13:58:23浏览次数:61  
标签:ints 平方 数组 nums int head tail 有序

给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。

 

示例 1:

输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]
示例 2:

输入:nums = [-7,-3,2,3,11]
输出:[4,9,9,49,121]
 

提示:

1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums 已按 非递减顺序 排序
 

class Solution {
   public int[] sortedSquares(int[] nums) {
        int[] ints = new int[nums.length];
        int n = nums.length - 1;//新数组赋值索引
        int head = 0;
        int tail = nums.length - 1;
        while (n > 0) {
            if (nums[head] * nums[head] > nums[tail] * nums[tail]) {
                ints[n--] = nums[head] * nums[head];
                head++;
            } else {
                ints[n--] = nums[tail] * nums[tail];
                tail--;
            }
        }
        ints[0] = nums[tail] * nums[tail];
        return ints;
    }
}

题目来自力扣题库977

 

标签:ints,平方,数组,nums,int,head,tail,有序
From: https://www.cnblogs.com/itzkd/p/16657841.html

相关文章

  • 后缀数组
    https://oiwiki.org/string/sa/性质1:\(sa[rk[i]]=rk[sa[i]]\)翻译一下,即记i的排名为\(k\),\(sa[k]=i\),排名为\(i\)的后缀的排名为\(i\)。性质2:$\forallx\in......
  • Day06__数组
    数组数组的定义数组的声明和创建packagearray;//数组的声明和创建publicclassDemo01{publicstaticvoidmain(String[]args){int[]nums;//......
  • Stream流进行数组排序
    ​考虑一个数组:int[]nums={9,6,5,7,4,8,3,1,2};对于数组,列举几个转换Stream流的操作及返回值://返回Stream对象,但泛型为int[]数组Stream<int[]>nums1=Stream.of(n......
  • 数组和字符串的相互转换
      var arr = [1, 2, 3, 4];    var arr2 = arr;    var str = arr.toString(); // 将数组转换为字符串    console.log(str); // 1,2,......
  • 数组的基本用例
    数组的基本用例int[]arr={1,7,3,4,5};//定义一个数组遍历并打印数组内所有元素for(inti=0;i<arr.length;i++){System.out.println(arr[i]);......
  • 通过 Infinity 和 -Infinity 查找数组中最大和最小值
    functionfindMaxNum(numbers){letmax=-Infinity;for(constnofnumbers){if(n>max){max=n;}}returnmax;}functionfindMi......
  • 数组去重的几种方式
    1、利用Map数据结构去重1letarr=[1,2,3,4,3,2,3,4,6,7,6];2letunique=(arr)=>{3letseen=newMap();4returnarr.filter((item......
  • 数组初始化
    memset(a,false,sizeof(a));//将bool型a数组初始化为false0x3f3f3f3f//INT_MAX的一半memset(a,0x3f3f3f3f,sizeof(a));//将a数组初始化为0x3f3f3f3fmemset(a,0,sizeo......
  • 动态数组
    动态数组1.vector1.1vector说明vector是向量类型,可以容纳许多类型的数据,因此也被称为容器(可以理解为动态数组,是封装好了的类)进行vector操作前应添加头文件......
  • 一维数组
    一#include<bits/stdc++.h>usingnamespacestd;intmain(){ inta[3]; cin>>a[0]; cin>>a[1]; cin>>a[2]; cout<<a[0]<<endl; cout<<a[1]<<endl;......