Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
来源:互联网 发布:网络文学作品 编辑:程序博客网 时间:2024/05/09 19:11
一、题目叙述:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array nums = [1,1,1,2,2,3]
,
Your function should return length = 5
, with the first five elements of nums being 1
, 1
, 2
, 2
and 3
. It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question.
二、解题思路:
Medium题。
思路:
(1)倒着遍历数组,若当前元素与其前前一个元素的值不同,计数加1;否则,将后续元素前移。
(2)注意当数组元素小于等于2的情况。
三、源码:
import java.util.Arrays;public class Solution { public int removeDuplicates(int[] nums){ if (nums.length <= 2) return nums.length; int count = 2; for (int i = nums.length - 1; i >= 2; i--) { if (nums[i] != nums[i - 2]) count ++; else for (int j = i; j < nums.length - 1; j ++) nums[j] = nums[j + 1]; } System.out.println(Arrays.toString(nums)); return count; } public static void main(String args[]) { Solution solution = new Solution(); int[] nums = {1, 1, 1, 2, 2, 3}; System.out.println(solution.removeDuplicates(nums)); } }
0 0
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- Leetcode 80. Remove Duplicates from Sorted Array II(从已排序数组中移除重复元素)
- [leetcode 26]Remove Duplicates from Sorted Array——移除排序数组中重复元素
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- LeetCode 26 Remove Duplicates from Sorted Array(从已排序数组中移除重复元素)
- Leetcode刷题记——26. Remove Duplicates from Sorted Array(删除数组重复元素)
- Remove Duplicates from Sorted Array——移除排序数组中重复元素
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- [LeetCode-26] Remove Duplicates from Sorted Array(移除数组重复元素)
- LeetCode 82 Remove Duplicates from Sorted List II(从已排序链表中移除重复元素)(Linked List)(*)
- LeetCode-26-Remove Duplicates from Sorted Array(消除已排序数组中的重复元素)
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- leetcode 4. 移除有序数组中的重复元素 Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array II 移除重复的元素(重)
- 26. Remove Duplicates from Sorted Array(移除有序数组中的重复元素)
- (有序数组中移除重复元素)Remove Duplicates from Sorted Array
- LeetCode | Remove Duplicates from Sorted Array II(删除重复的元素2)
- LeetCode 83 Remove Duplicates from Sorted List(从已排序链表中移除重复元素)(Linked List)(*)
- 软件测试面试常考点
- java安全架构____openssl生成数字证书
- this指针在类的成员函数中的传递
- 求具有abcd=(ab+cd)2性质的四位数
- UOJ#267 BZOJ4731【清华集训2016】魔法小程序
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- C++返回指针的函数范例
- 素数
- 线性模型
- 字符数组什么时候可以看做是一个字符串?
- js封装-简单雪花插件
- js解析json报错
- LeetCode作业Majority Element
- golang中读写锁RWMutex和通用锁Mutex的使用