标签:sam tar imm 日期 www script 开始 href jimmy
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.
Java Solution:
Runtime beats 27.80%
完成日期:07/29/2017
关键词:Array
关键点:多设一个int count 来记录出现重复数字的次数
1 public class Solution 2 { 3 public int removeDuplicates(int[] nums) 4 { 5 if(nums.length <= 2) 6 return nums.length; 7 8 int pointer = 0; 9 int count = 1; 10 11 for(int i=1; i<nums.length; i++) 12 { 13 // if this number is different than pointer number 14 if(nums[i] != nums[pointer]) 15 { 16 pointer++; 17 nums[pointer] = nums[i]; 18 count = 1; 19 } 20 else // if this number is same as pointer number 21 { 22 if(count == 1) // if it is second same number 23 { 24 pointer++; 25 nums[pointer] = nums[i]; 26 count++; 27 } 28 } 29 } 30 31 return pointer + 1; 32 } 33 }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
LeetCode 80. Remove Duplicates from Sorted Array II (从有序序列里移除重复项之二)
标签:sam tar imm 日期 www script 开始 href jimmy
原文地址:http://www.cnblogs.com/jimmycheng/p/7258157.html