https://github.com/dolphinmind/datastructure/tree/datastructure-array
主类
package com.github.dolphinmind.array.binarysearch;
/**
* @author dolphinmind
* @ClassName SquaresOfASortedArray
* @description 977. 有序数组的平方
* 分析:有移除元素{@link RemoveElement}中的双向指针的思路,不过当前解法是开辟一个新数组
* @date 2024/7/31
*/
public class SquaresOfASortedArray {
public int[] twoPointersReverse(int[] nums) {
int left = 0;
int right = nums.length - 1;
int[] result = new int[nums.length];
int index = result.length - 1;
while (left <= right) {
if (Math.pow(nums[left], 2) > Math.pow(nums[right], 2)) {
result[index--] = (int) Math.pow(nums[left], 2);
++left;
} else {
result[index--] = (int) Math.pow(nums[right], 2);
--right;
}
}
return result;
}
}
测试类
package com.github.dolphinmind.array.binarusearch;
import com.github.dolphinmind.array.binarysearch.SquaresOfASortedArray;
import org.junit.Test;
/**
* @author dolphinmind
* @ClassName SquaresOfASortedArray
* @description
* @date 2024/7/31
*/
public class SquaresOfASortedArrayTest {
@Test
public void test_twoPointersReverse() {
int[] nums = {-4,-1,0,3,10};
// int[] nums = {};
int[] result = new SquaresOfASortedArray().twoPointersReverse(nums);
for (int i : result) {
System.out.print(i + " ");
}
}
}
标签:977,SquaresOfASortedArray,nums,int,dolphinmind,right,result,LeetCode
From: https://www.cnblogs.com/dolphinmind/p/18335571