leetcode_1线性表_1数组_1&2Remove Duplicates from Sorted Array I & II

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之类的用

转载于:https://www.cnblogs.com/Jay-Zen/p/4009979.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值