【leetcode】Remove Duplicates from Sorted Array 1和2
2014-09-05 16:56
344 查看
双指针的问题,去掉冗余元素的时候,数据结构是数组的时候常常采用
1题目:
Given input array A =
Your function should return length =
Given sorted array A =
Your function should return length =
1题目:
Given input array A =
[1,1,2],
Your function should return length =
2, and A is now
[1,2].
class Solution { public int removeDuplicates(int[] A) { int length=A.length; int index=0; for(int i=0;i<length;i++){ for(int j=i+1;j<length;j++){ if(A[i]!=A[j]){ break; } else{ i++; } } A[index++]=A[i]; } return index; } }题目2:比题目一多的条件是相同的元素可以最多存在两次,所以加入一个count计算重复元素出现的次数,注意count是从1开始的
Given sorted array A =
[1,1,1,2,2,3],
Your function should return length =
5, and A is now
[1,1,2,2,3].
public class Solution { public int removeDuplicates(int[] A) { int length=A.length; int index=0; int count=0; for(int i=0;i<length;i++){ count=1;//此处需注意 for(int j=i+1;j<length;j++){ if(A[i]!=A[j]){ break; } else{ count++; i++; } } if(count>=2) { A[index++]=A[i]; A[index++]=A[i]; } else A[index++]=A[i]; } return index; } }
相关文章推荐
- LeetCode @ Remove Duplicates from Sorted Array 数组去重
- [leetcode] Remove Duplicates from Sorted Array
- 【leetcode】Remove Duplicates from Sorted Array I & II(middle)
- LeetCode 72 Remove Duplicates from Sorted Array II
- 【Leetcode】Remove Duplicates from Sorted Array II
- Leetcode- Remove Duplicates from Sorted Array
- LeetCode-Remove Duplicates from Sorted Array
- Leetcode-Remove Duplicates from Sorted Array
- [LeetCode]26. Remove Duplicates from Sorted Array
- LeetCode-Remove Duplicates from Sorted Array II (删除重复元素,使重复次数最多N次)
- LeetCode Remove Duplicates from Sorted Array II
- [leetcode刷题] Remove Duplicates from Sorted Array
- LeetCode - Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II 有序数组中去除重复项之二
- LeetCode-----26. Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- Remove Duplicates From Sorted Array leetcode java
- Leetcode || Remove Duplicates from Sorted Array
- Leetcode--Remove Duplicates from Sorted Array
- leetcode 26. Remove Duplicates from Sorted Array