leetcode 【 Remove Duplicates from Sorted Array 】python 实现
2015-01-16 21:31
141 查看
题目:
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 =
代码:oj测试通过 Runtime: 143 ms
思路:
首先排除长度为0的special case
使用双指针技巧:用curr指针记录不含有重复元素的数据长度;另一个指针i从前往后走
Tips: 注意curr是数组元素的下标从0开始,所以再最后返回时要返回curr+1
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].
代码:oj测试通过 Runtime: 143 ms
class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): if len(A) == 0: return 0 curr = 0 for i in range(0, len(A)): if A[curr] != A[i] : A[curr+1],A[i] = A[i],A[curr+1] curr += 1 return curr+1
思路:
首先排除长度为0的special case
使用双指针技巧:用curr指针记录不含有重复元素的数据长度;另一个指针i从前往后走
Tips: 注意curr是数组元素的下标从0开始,所以再最后返回时要返回curr+1
相关文章推荐
- [LeetCode]3 Longest Substring Without Repeating Characters (C++,Python实现)
- [LeetCode]5 Longest Palindromic Substring(C++,Python实现)
- leetcode 【 Reverse Linked List II 】 python 实现
- leetcode 【 Merge k Sorted Lists 】python 实现
- leetcode 【 Partition List 】python 实现
- [LeetCode]1 Two Sum(C++,Python实现)
- leetcode 【 Remove Element 】python 实现
- leetcode 【 Insertion Sort List 】 python 实现
- leetcode 【 Linked List Cycle II 】 python 实现
- leetcode 【 Convert Sorted List to Binary Search Tree 】python 实现
- LeetCode 2. Add Two Numbers (C++/python/js实现)
- leetcode 【 Remove Duplicates from Sorted List 】 python 实现
- leetcode 【 Remove Nth Node From End of List 】 python 实现
- leetcode 【 Sort List 】 python 实现
- leetcode 【Rotate List 】python 实现
- [LeetCode]4 Add Two Numbers(C++,Python实现)
- leetcode 【 Linked List Swap Nodes in Pairs 】 python 实现
- leetcode 【 Merge Two Sorted Lists 】 python 实现
- leetcode 【 Reorder List 】python 实现
- leetcode 【 Add Two Numbers 】 python 实现