leetCode 26.Remove Duplicates from Sorted Array(删除数组重复点) 解题思路和方法
2015-07-07 20:19
555 查看
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.
思路:此题比较简单,大意是将数组中重复点删除,然后返回新数组的长度。数组中前n个数就是新的数组。唯一难点是不能用额外空间。
详细代码如下:
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.
思路:此题比较简单,大意是将数组中重复点删除,然后返回新数组的长度。数组中前n个数就是新的数组。唯一难点是不能用额外空间。
详细代码如下:
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length <= 1){ return nums.length; } int len = 1;//新的长度,至少为1,以下循环从i=1开始 for(int i = 1; i < nums.length; i++){ if(nums[i] != nums[i-1]){//不等于前一个元素,长度+1 nums[len++] = nums[i];//将新的元素装到前len个 } } return len; } }
相关文章推荐
- javascript笔记02:严格模式的特定要求
- 集群安装完毕,该如何测试和使用集群-hadoop单机(伪分布)
- 多线程调用fork的问题 连续捕捉相同信号的问题
- TJU4111-Binomial efficient(数论)
- TCP知识点记录
- COJ 0801 非传统题(一)
- Murano PTL&Core
- 为什么使用剪切板时都用GlobalAlloc分配内存
- Asp与Asp.Net
- 图像掩膜的作用
- 五:二叉树中和为某一直的路径
- 【BigData】100 open source Big Data architecture papers for data professionals
- FileZilla && itms-services
- eclipse执行debug as出现问题
- STL - vector容器
- STL - vector容器
- NYOJ 596 谁是最好的Coder
- 二、hadoop伪分布搭建
- leetcode-145-Binary Tree Postorder Traversal
- 【剑指offer】面试题30:最小的 K 个数