首页 > 代码库 > Remove Duplicates from Sorted Array
Remove Duplicates from Sorted Array
Remove Duplicates from Sorted Array
Total Accepted: 22879 Total Submissions: 70824My SubmissionsGiven 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 = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
这题与Remove Duplicates from Sorted List类似,只不过换成了数组,要把排好序的数组的元素变为不重复,且要求原地操作。
class Solution { public: int removeDuplicates(int A[], int n) { int new_arr_cur, arr_cur; new_arr_cur = arr_cur = 0; while (arr_cur < n) { A[new_arr_cur++] = A[arr_cur]; // assign //skip duplicates while (arr_cur < n && A[arr_cur] == A[new_arr_cur - 1]) { arr_cur++; } } return new_arr_cur; } };
Remove Duplicates from Sorted Array II
Total Accepted: 17014 Total Submissions: 55726My SubmissionsFollow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
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]
.
这里是最多允许两次重复,要在上面的代码进行修改。
class Solution { public: int removeDuplicates(int A[], int n) { int new_arr_cur, arr_cur, count; new_arr_cur = arr_cur = 0; const int DUPLICATE_NUM = 2; while (arr_cur < n) { A[new_arr_cur++] = A[arr_cur++]; count = 1; //add allowed duplicates while (count < DUPLICATE_NUM && arr_cur < n && A[arr_cur] == A[new_arr_cur - 1]) { A[new_arr_cur++] = A[arr_cur++]; count++; } //skip leftmost duplicate while (arr_cur < n && A[arr_cur] == A[new_arr_cur - 1]) { arr_cur++; } } return new_arr_cur; } };
Remove Duplicates from Sorted Array
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。