LeetCode----Remove Duplicates from Sorted Array
来源:互联网 发布:公司内部网络建设 编辑:程序博客网 时间:2024/05/14 19:12
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 nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the new length.
分析:
从已排序的数组中“删除”重复的元素,要求O(1)的空间。简单题。
使用两个指针p,q,一个指针遍历数组,另一个指针纪录无重复元素的数组的下标。
Python代码:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ nums_len = len(nums) if nums_len <= 1: return nums_len p, q = 1, 1 while p < nums_len: if nums[p] != nums[p - 1]: nums[q] = nums[p] q += 1 p += 1 return q
C++代码:
class Solution {public: int removeDuplicates(vector<int>& nums) { int nums_len = nums.size(); if(nums_len <= 1){ return nums_len; } for(int p = 1, q = 1; p < nums_len; p++){ if(nums[p] != nums[p - 1]){ nums[q++] = nums[p]; } } return q; }};
0 0
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- leetcode 35: Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array
- Leetcode: Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array
- [leetcode]Remove Duplicates from Sorted Array II
- 从 NSURLConnection 到 NSURLSession
- JPA入门之环境的搭建
- Bootstrap布局
- java 工具类 ---反射字段值封装到对象中
- NSURLSession使用说明及后台工作流程分析
- LeetCode----Remove Duplicates from Sorted Array
- 右移运算符>>和>>>的区别
- grunt学习笔记七:插件安装
- java多线程 学习笔记(二)——线程执行器 Executor
- 模式识别中分级聚类算法
- 曲线拟合
- 解决KVM中鼠标不同步问题
- 导出android测试机中数据库的步骤
- android设置外部字体