给定一个数组找出不含重复数字的最长子数组的长度用java
可以使用滑动窗口的方法来解决这个问题。
import java.util.HashSet;
public class LongestSubarrayWithoutDuplicates {
public static int findLongestSubarrayLength(int[] nums) {
int n = nums.length;
int maxLength = 0;
int left = 0;
int right = 0;
HashSet<Integer> set = new HashSet<>();
while (right < n) {
if (!set.contains(nums[right])) {
set.add(nums[right]);
maxLength = Math.max(maxLength, right - left + 1);
right++;
} else {
set.remove(nums[left]);
left++;
}
}
return maxLength;
}
public static void main(String[] args) {
int[] nums = {1, 2, 3, 1, 2, 3, 4, 5};
int maxLength = findLongestSubarrayLength(nums);
System.out.println("The length of the longest subarray without duplicates is: " + maxLength);
}
}
输出结果为:
The length of the longest subarray without duplicates is: 5
时间复杂度:O(n) 空间复杂度:O(k),其中 k 是数组中不重复数字的个数。
原文地址: https://www.cveoy.top/t/topic/i6gg 著作权归作者所有。请勿转载和采集!