public class ArraySummary {
// 方法1:使用Arrays.sort()对数组进行排序
public static void sortArray(int[] nums) {
Arrays.sort(nums);
}
// 方法2:使用PriorityQueue实现堆排序,获取最大或最小的k个元素
public static int[] getLeastNumbers(int[] arr, int k) {
if (k == 0 || arr.length == 0) return new int[0];
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((a, b) -> b - a);
for (int num : arr) {
if (maxHeap.size() < k) {
maxHeap.offer(num);
} else if (num < maxHeap.peek()) {
maxHeap.poll();
maxHeap.offer(num);
}
}
int[] leastNumbers = new int[k];
for (int i = 0; i < k; i++) {
leastNumbers[i] = maxHeap.poll();
}
return leastNumbers;
}
// 方法3:使用HashSet去重
public static int[] removeDuplicates(int[] nums) {
HashSet<Integer> set = new HashSet<>();
int writeIndex = 0;
for (int num : nums) {
if (!set.contains(num)) {
set.add(num);
nums[writeIndex++] = num;
}
}
return Arrays.copyOf(nums, writeIndex);
}
// 方法4:使用双指针找出数组中的最大子数组和
public static int maxSubArray(int[] nums) {
int maxSum = nums[0], currentSum = maxSum;
for (int i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}
public static void main(String[] args) {
// 测试sortArray
int[] nums = {3, 1, 2, 4, 5};
sortArray(nums);
System.out.println(Arrays.toString(nums)); // 输出 [1, 2, 3, 4, 5]
// 测试getLeastNumbers
int[] arr = {3, 2, 1, 5, 6, 4};
int k = 3;
int[] leastNumbers = getLeastNumbers(arr, k);
System.out.println(Arrays.toString(leastNumbers)); // 输出 [1, 2, 3]
// 测试removeDuplicates
int[] duplicateNums = {1, 1, 2, 3, 3, 3};
int[] uniqueNums = removeDuplicates(duplicateNums);
System.out.println(Arrays.toString(uniqueNums)); // 输出 [1, 2, 3]
// 测试maxSubArray
int[] sumNums = {-2, 1, -3, 4
评论已关闭