Java数组进阶挑战:解剖那些“变态”题300


Java数组是程序员日常开发中不可或缺的数据结构,其简洁高效的特性使得它广泛应用于各种场景。然而,一些看似简单的数组问题,经过巧妙的变形,就能成为令人头疼的“变态题”,考验程序员对数组操作的深度理解以及算法设计的功底。本文将深入探讨几类常见的“变态”Java数组题,并结合代码示例,逐步揭示其解题思路和技巧。

一、高频元素查找的变种

经典的数组问题包括查找数组中出现频率最高的元素。但“变态题”会增加难度,例如:要求在O(n)时间复杂度内完成,或者限定空间复杂度,又或者加入元素范围限制等条件。以下是一个例子:在一个包含大量整数的数组中,找到出现次数超过一半的元素,如果不存在这样的元素,则返回-1。 O(n)时间复杂度和O(1)空间复杂度的要求,是这类问题的关键难点。
import ;
import ;
public class MajorityElement {
public static int findMajorityElement(int[] nums) {
if (nums == null || == 0) {
return -1;
}
Map countMap = new HashMap();
for (int num : nums) {
(num, (num, 0) + 1);
}
for ( entry : ()) {
if (() > / 2) {
return ();
}
}
return -1;
}

//摩尔投票算法 O(n)时间复杂度 O(1)空间复杂度
public static int findMajorityElementOptimized(int[] nums) {
int candidate = nums[0];
int count = 1;
for (int i = 1; i < ; i++) {
if (nums[i] == candidate) {
count++;
} else {
count--;
if (count == 0) {
candidate = nums[i];
count = 1;
}
}
}
count = 0;
for (int num : nums) {
if (num == candidate) {
count++;
}
}
return count > / 2 ? candidate : -1;
}

public static void main(String[] args) {
int[] nums1 = {2, 2, 1, 1, 1, 2, 2};
int[] nums2 = {3,2,3};
int[] nums3 = {1,2,3,4,5};
("Majority element (HashMap): " + findMajorityElement(nums1)); // Output: 2
("Majority element (HashMap): " + findMajorityElement(nums2)); // Output: 3
("Majority element (HashMap): " + findMajorityElement(nums3)); // Output: -1
("Majority element (Optimized): " + findMajorityElementOptimized(nums1)); // Output: 2
("Majority element (Optimized): " + findMajorityElementOptimized(nums2)); // Output: 3
("Majority element (Optimized): " + findMajorityElementOptimized(nums3)); // Output: -1
}
}

代码中提供了两种解法:一种使用HashMap,易于理解,但空间复杂度较高;另一种是摩尔投票算法,时间复杂度和空间复杂度都更优。

二、旋转数组的查找问题

一个排序数组经过旋转后,查找目标元素就变得复杂。例如,一个排序数组[0,1,2,4,5,6,7] 旋转后变成[4,5,6,7,0,1,2],如何在O(log n)的时间复杂度内找到目标元素? 这就需要用到二分查找的变形技巧,需要仔细处理旋转点带来的边界条件。

public class RotatedSortedArraySearch {
public static int search(int[] nums, int target) {
int left = 0;
int right = - 1;
while (left

2025-06-18


上一篇:Java同步MongoDB数据:最佳实践与性能优化

下一篇:Java方法异常处理最佳实践:从捕获到优雅的错误处理