1.1.1 Remove Duplicates from Sorted Array
题目:
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 = [1,1,2],Your function should return length = 2, and A is now [1,2].
分析:
时间复杂度 O(n),空间复杂度 O(1),因为是排好序的。后一个和前一个比较,相同则不要(跳过),不同则放。一个的变量不断加,一直到数组长度不断取数,一个变量指向欲存数组的地址量。
以下是C++和PYTHON实现的代码:
1 class Solution { 2 public: 3 int removeDuplicates(int A[], int n) { 4 if(n == 0) return 0; 5 6 int p = 0; 7 for(int i = 0; i < n; i++) 8 { 9 if(A[p] != A[i]) 10 { 11 A[++p] = A[i]; 12 13 } 14 } 15 return p + 1; 16 } 17 };
1 class Solution: 2 # @param a list of integers 3 # @return an integer 4 def removeDuplicates(self, A): 5 if len(A) == 0: 6 return 0 7 8 p = 0 9 for i in A: 10 if A[p] != i: 11 p += 1 12 A[p] = i 13 return p + 1
1.1.2 Remove Duplicates from Sorted Array II
题目:
Follow 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]
.
分析:
因为排好序的,类似上体,只要可以允许连续两个相同元素存在,所以将待比的与已存好的倒数第二个去比。如果是3,或n,以此类推。
以下是JAVE和PYTHON的代码:
1 public class Solution { 2 public int removeDuplicates(int[] A) { 3 if (A.length <= 2) return A.length; 4 5 int p = 2; 6 for (int i=2; i < A.length; i++) 7 if (A[i] != A[p -2]) 8 A[p++] = A[i]; 9 return p; 10 } 11 }
1 class Solution: 2 # @param A a list of integers 3 # @return an integer 4 def removeDuplicates(self, A): 5 if (len(A) <= 2): return len(A) 6 7 p = 2 8 for i in range(2,len(A)): 9 if (A[i] != A[p - 2]): 10 A[p] = A[i] 11 p += 1 12 return p
小结:
JAVE中,A.length 后没有()
注意 p++和++p的区别
注意初始条件
PYTHON中没有++,——,得 p += 1之类的用
时间: 2024-10-11 21:31:29