LeetCode | Remove Duplicates from Sorted Array(删除有序数组的重复元素)
2014-07-08 23:47
260 查看
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A =
Your function should return length =
删除重复的数,并返回数组的长度
题目解析:
这道题目可以从快速排序算法得到启发:快排有两种,一种从左向右遍历,碰到比key大的,就将放到后面,再从后向前遍历;另一种是设两个下标指针,i和j,i指向当前遍历的数据里面都比key小的数据,i->j-1之间都是大于key的数据,j指向当前要判断的数据,如果arr[j]<=key,就将arr[i+1]和arr[j]交换。
但这个题目当中只是让删除数据,我们可以利用上述第二种方法,但不交换,直接arr[i+1] = arr[j]。不过具体实现的时候,和快排有一点点差别。
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array A =
[1,1,2],
Your function should return length =
2, and A is now
[1,2].
删除重复的数,并返回数组的长度
题目解析:
这道题目可以从快速排序算法得到启发:快排有两种,一种从左向右遍历,碰到比key大的,就将放到后面,再从后向前遍历;另一种是设两个下标指针,i和j,i指向当前遍历的数据里面都比key小的数据,i->j-1之间都是大于key的数据,j指向当前要判断的数据,如果arr[j]<=key,就将arr[i+1]和arr[j]交换。
但这个题目当中只是让删除数据,我们可以利用上述第二种方法,但不交换,直接arr[i+1] = arr[j]。不过具体实现的时候,和快排有一点点差别。
#include <stdio.h> #include <stdlib.h> int RemoveDuplicates(int arr[],int len); int main() { int arr[10]; int n; while(scanf("%d",&n) != EOF){ for(int i = 0;i < n;++i) scanf("%d",&arr[i]); int len = RemoveDuplicates(arr,n); printf("len = %d\n",len); for(int i = 0;i < len;++i) printf("%d ",arr[i]); printf("\n"); } return 0; } int RemoveDuplicates(int arr[],int len) { int i,j; if(arr == NULL || len <= 0) return 0; i = 0; j = 1; while(j < len){ if(arr[i] != arr[j] && ++i != j) arr[i] = arr[j]; ++j; } return i+1; }
相关文章推荐
- leetcode 4. 移除有序数组中的重复元素 Remove Duplicates from Sorted Array
- Leetcode刷题记——26. Remove Duplicates from Sorted Array(删除数组重复元素)
- 【LeetCode-面试算法经典-Java实现】【026-Remove Duplicates from Sorted Array(删除排序数组中的重复元素)】
- Remove Duplicates from Sorted Array II 从有序数组里移除重复出现元素,最多重复出现2次 @LeetCode
- [Leetcode] Remove duplicates from sorted array 从已排序的数组中删除重复元素
- LeetCode: Remove Duplicates from Sorted Array II(在排序数组中删除重复元素)
- 删除有序数组中的重复元素 Remove Duplicates from Sorted Array
- LeetCode Remove Duplicates from Sorted Array II 删除整型数组中的重复元素并返回剩下元素个数2
- Remove Duplicates from Sorted Array 有序数组删除重复元素 @LeetCode
- leetcode:26&80 Remove Duplicates from Sorted Array 删除数组中的重复元素
- [Leetcode] Remove duplicates from sorted array ii 从已排序的数组中删除重复元素
- LeetCode 26. Remove Duplicates from Sorted Array(移除有序数组的重复元素)
- LeetCode-26:Remove Duplicates from Sorted Array (清除数组重复元素)
- Leetcode刷题记—— Remove Duplicates from Sorted Array II(已排序数组移除重复元素2)
- leetCode 26.Remove Duplicates from Sorted Array(删除数组重复点) 解题思路和方法
- LeetCode OJ 之 Remove Duplicates from Sorted Array II (删除有序数组中重复的数-二)
- [LeetCode] Remove Duplicates from Sorted Array 有序数组中去除重复项
- (有序数组中移除重复元素)Remove Duplicates from Sorted Array
- LeetCode-26-Remove Duplicates from Sorted Array(消除已排序数组中的重复元素)
- LeetCode 26 Remove Duplicates from Sorted Array (移除有序数组中重复数字)