leetcode80. Remove Duplicates from Sorted Array II
来源:互联网 发布:电算化软件有哪些 编辑:程序博客网 时间:2024/05/22 07:09
80. Remove Duplicates from Sorted Array II
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.
解法一
相同元素的个数依次累加。注意从1开始。
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 0 && nums == null) { return 0; } int i = 1, j = 1; int count = 1; while (j < nums.length) { if (nums[j] != nums[j - 1]) { count = 1; nums[i++] = nums[j]; } else { if (count < 2) { nums[i++] = nums[j]; count++; } } j++; } return i; }}
解法二
判断i-2元素是否小于该元素,小于就把该元素添加到数组里。
public class Solution { public int removeDuplicates(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int i = 0; for (int num : nums) { if (i < 2 || nums[i - 2] < num) { nums[i++] = num; } } return i; }}
阅读全文
0 0
- leetcode80 Remove Duplicates from Sorted Array II
- leetcode80. Remove Duplicates from Sorted Array II
- leetcode80 Remove Duplicates from Sorted Array II
- LeetCode80. Remove Duplicates from Sorted Array II
- leetcode80~Remove Duplicates from Sorted Array II
- leetcode80. Remove Duplicates from Sorted Array II
- LeetCode80 Remove Duplicates from Sorted Array II
- LeetCode80——Remove Duplicates from Sorted Array II
- leetcode80[medium]--Remove Duplicates from Sorted Array II
- [LeetCode80]Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- PYTHON ANACONDA装FFMPEG imagemagick
- Java包命名规则
- Ubuntu1404下安装GCC 4.7.x
- Redis常用命令
- 判断有向图是否有环
- leetcode80. Remove Duplicates from Sorted Array II
- JDBC 的常用 API
- 草根程序员转型做项目管理走过的点点滴滴之一屋不扫何以扫天下
- Sudoku Killer(深搜)
- jar 打包详解
- marc做焊接仿真的基本流程
- 基于opencv的车牌识别(二)车牌定位与提取预处理操作思路
- CentOS7搭建FastDFS V5.11分布式文件系统及Java整合详细过程(四)
- mysql 联合索引 too long 错误