Leetcode c语言-Remove Duplicates from Sorted Array
来源:互联网 发布:新代数控车床编程实例 编辑:程序博客网 时间:2024/06/08 17:49
Title:
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.
这道题目很简单,但如果只按照题目意思会更简单,题目意思是只需要返回长度,而不用管其他任何事。
但如果你天真的只返回长度,而不修改数组。那么你会发现你胸有成竹的几行代码,会报错,原因就是你没有对应的修改数组。也就是说也要把数组中重复的元素删掉。但题目要求没有提到这个,让人有点无语。也终于明白为什么这道题的踩那么多了:
因此,我们需要修改数组,而且不能创建新的数组,只能在固定空间修改。
很好办,遍历每一个元素,然后如果这个元素与它的下一个元素不同,说明它是唯一的,这个时候保存即可。如果相同,就不做任何操作,继续遍历下一个元素。
solution:
int removeDuplicates(int* nums, int numsSize) { int len=0; int res; int i; if (numsSize==0) return 0; if (numsSize==1) return 1; for (i=0;i<numsSize;i++) { if (nums[i]!=nums[i+1]) { nums[len]=nums[i]; len++; } else if(i==numsSize-1 && nums[i]==nums[i+1]) { nums[len]=nums[i]; len++; } } return len;}
要注意的一种情况,就是最后1个元素如果是0的话,i+1表示数组的结束符,也是0,这个时候要做特殊处理,保证0存入。
else if(i==numsSize-1 && nums[i]==nums[i+1]) { nums[len]=nums[i]; len++;
- [leetcode](Remove Duplicates from Sorted Array II C语言实现)
- [C语言][LeetCode][26]Remove Duplicates from Sorted Array
- [leetcode]Remove Duplicates from Sorted Array C语言
- [C语言][LeetCode][80]Remove Duplicates from Sorted Array II
- Leetcode c语言-Remove Duplicates from Sorted Array
- 4---LeetCode【tag: Array】【Remove Duplicates from Sorted Array】|C语言|总结
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- [C++]LeetCode: 2 Remove Duplicates from Sorted Array
- [C++]LeetCode: 72 Remove Duplicates from Sorted Array II
- [LeetCode] 026. Remove Duplicates from Sorted Array (Easy) (C++/Java)
- 【leetcode c++】26 Remove Duplicates from Sorted Array
- 【leetcode c++】80 Remove Duplicates from Sorted Array II
- [leetcode-26]Remove Duplicates from Sorted Array(C)
- [leetcode-80]Remove Duplicates from Sorted Array II(C)
- leetcode刷题系列C++-Remove Duplicates From Sorted Array
- 【LeetCode-26】 Remove Duplicates from Sorted Array(C++)
- 【C++】【LeetCode】26. Remove Duplicates from Sorted Array
- 数据结构java实现
- Mybatis高级查询(一)
- JavaScript: switch用法及注意事项
- Android 设计模式
- token相关
- Leetcode c语言-Remove Duplicates from Sorted Array
- 3SumCloset
- 做自媒体文章的淘宝客面对这两个节日所要注意的几点!
- Http通讯类
- @RestController注解与@Controller 注解的区别
- 微信小程序开发经验总结(五)
- ubuntu14.04下adb devices找不到设备
- iOS Failed to create IXPlaceholder for app bundle ID***
- BAT Android工程师面试流程解析+还原最真实最完整的一线公司面试题