打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
leetCode 26.Remove Duplicates from Sorted Array(删除数组重复点) 解题思路和方法
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个数就是新的数组。唯一难点是不能用额外空间。
详细代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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;
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
LeetCode之Remove Duplicates from Sorted Array II
0977. Squares of a Sorted Array (E)
0081. Search in Rotated Sorted Array II (M)
​LeetCode刷题实战532:数组中的K-diff数对
八十一、最快最优的快速排序和优化
LeetCode实战:寻找两个有序数组的中位数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服