淮安市淮阴区建设局网站,wordpress acg主题,dedecms中餐网站模板,wordpress 关闭 ssl删除有序数组中的重复项 其他算法导航栏
给你一个 非严格递增排列 的数组 nums #xff0c;请你 原地 删除重复出现的元素#xff0c;使每个元素 只出现一次 #xff0c;返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。
考虑 …删除有序数组中的重复项 其他算法导航栏
给你一个 非严格递增排列 的数组 nums 请你 原地 删除重复出现的元素使每个元素 只出现一次 返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回 nums 中唯一元素的个数。
考虑 nums 的唯一元素的数量为 k 你需要做以下事情确保你的题解可以被通过
更改数组 nums 使 nums 的前 k 个元素包含唯一元素并按照它们最初在 nums 中出现的顺序排列。nums 的其余元素与 nums 的大小不重要。 返回 k 。
示例 1
输入nums [1,1,2] 输出2, nums [1,2,_] 解释函数应该返回新的长度 2 并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。
解题思路
1、由于数组是非严格递增排列的重复元素一定是相邻的。我们可以使用双指针技巧来解决这个问题。2、一个指针用于遍历数组另一个指针用于记录下一个不重复元素的位置。3、遍历数组当遇到不重复的元素时将其移动到指定位置并将指定位置后移一位。
Java实现
public class RemoveDuplicates {public int removeDuplicates(int[] nums) {if (nums.length 0) {return 0;}int j 1;for (int i 1; i nums.length; i) {if (nums[i] ! nums[i - 1]) {nums[j] nums[i];j;}}return j;}public static void main(String[] args) {RemoveDuplicates removeDuplicates new RemoveDuplicates();int[] nums1 {1, 1, 2};int result1 removeDuplicates.removeDuplicates(nums1);System.out.println(Test Case 1:);System.out.println(Original Array: [1, 1, 2]);System.out.println(New Length: result1); // Expected: 2System.out.println(New Array: Arrays.toString(Arrays.copyOfRange(nums1, 0, result1))); // Expected: [1, 2]int[] nums2 {0, 0, 1, 1, 1, 2, 2, 3, 3, 4};int result2 removeDuplicates.removeDuplicates(nums2);System.out.println(\nTest Case 2:);System.out.println(Original Array: [0, 0, 1, 1, 1, 2, 2, 3, 3, 4]);System.out.println(New Length: result2); // Expected: 5System.out.println(New Array: Arrays.toString(Arrays.copyOfRange(nums2, 0, result2))); // Expected: [0, 1, 2, 3, 4]}
}
时间空间复杂度
时间复杂度 遍历一次数组时间复杂度为 O(n)其中 n 是数组的长度。空间复杂度 使用了常数级的额外空间空间复杂度为 O(1)。