26. Remove Duplicates from Sorted Array
来源:互联网 发布:营销型网站源码 编辑:程序博客网 时间:2024/05/17 00:05
转载自 http://algorithm.books.mafengshe.com/answer/26.html
26. 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.
题目翻译
给定一个已经排序好的数组,删除重复的元素,得到一个每个元素只显示一次的新数组,返回值为新数组的长度。
不要为另一个数组分配额外的空间,您必须使用常量内存来执行此操作。
例如,
给定输入数组nums = [1,1,2],
您的函数应返回长度2,同时数组被更新为nums = [1,2]。
解题方案
标签: Array
思路:
- 当数组长度为0或者1时,直接访问长度值即可,不存在重复元素。
- 如果超过1,则对数组进行遍历,使用index变量指向数组更新位置,i变量指向数组遍历位置。
- 如果nums[inde] != nums[i]成立,则先移动index,然后更新,否则不更新。
- 返回值index少加了一次,故而为index+1
代码:
class Solution { public int removeDuplicates(int[] nums) { if(nums.length == 0 || nums.length ==1) return nums.length; int index = 0; for(int i=1;i<nums.length;i++){ if(nums[index]!=nums[i]){ index++; nums[index] = nums[i]; } } return index+1; }}
- [LeetCode]26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- LeetCode 26. Remove Duplicates from Sorted Array
- LeetCode --- 26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- [Leetcode] 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 【leetcode】26. Remove Duplicates from Sorted Array
- 【leetcode】 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- [leetCode]26. Remove Duplicates from Sorted Array
- LeetCode 26.Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array LeetCode
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array
- 两年 100 期技术周报后,我收获了这四点
- 如何运营一个开源项目并取得较大影响力?
- spring+sprngMVC+MyBatis框架的整合
- AutoMapper的使用方法
- 同台电脑下,安装多个版本的jdk ,修改环境变量不起作用
- 26. Remove Duplicates from Sorted Array
- 训练集,测试集和验证集
- JVM内存区域详解
- Java 自定义对list进行排序
- springcloud_5(路由网关)
- 自然语言处理深度学习的7个应用
- 第六章 注解式控制器详解——跟着开涛Spring-(生产者、消费者请求限定)
- 论怎样判断字母是大写还是小写
- 语义分割中的深度学习方法全解:从FCN、SegNet到各版本DeepLab