算法:删除排序数组中的重复项||
生活随笔
收集整理的這篇文章主要介紹了
算法:删除排序数组中的重复项||
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個排序數組,你需要在原地刪除重復出現的元素,使得每個元素最多出現兩次,返回移除后數組的新長度。
不要使用額外的數組空間,你必須在原地修改輸入數組并在使用 O(1) 額外空間的條件下完成。
示例 1:中等難度
給定 nums = [1,1,1,2,2,3],
函數應返回新長度 length = 5, 并且原數組的前五個元素被修改為 1, 1, 2, 2, 3 。
你不需要考慮數組中超出新長度后面的元素。
示例 2:
給定 nums = [0,0,1,1,1,1,2,3,3],
函數應返回新長度 length = 7, 并且原數組的前五個元素被修改為 0, 0, 1, 1, 2, 3, 3 。
你不需要考慮數組中超出新長度后面的元素。
//刪除數組中重復的元素,不能使用額外的空間class Solution {public int[] remElement(int[] arr, int index) { // 需要對數據做移動操作for (int i = index + 1; i < arr.length; i++) {arr[i - 1] = arr[i];}return arr;} public int removeDuplicates(int[] nums) {int i = 1, count = 1, length = nums.length;while (i < length) {if (nums[i] == nums[i - 1]) {count++;if (count > 2) {this.remElement(nums, i);i--;length--;}} else {count = 1;}i++;}return length;} }//雙指針原地修改數組 class Solution {public int removeDuplicates(int[] nums) {int j = 1, count = 1;for (int i = 1; i < nums.length; i++) {if (nums[i] == nums[i - 1]) {count++; } else {count = 1;}if (count <= 2) {nums[j++] = nums[i];}}return j;} }參考鏈接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array-ii/solution/shan-chu-pai-xu-shu-zu-zhong-de-zhong-fu-xiang-i-7/
總結
以上是生活随笔為你收集整理的算法:删除排序数组中的重复项||的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 算法:删除链表中重复的元素||
- 下一篇: 算法:搜索二维矩阵