[Leetcode]_26 Remove Duplicates from Sorted Array
来源:互联网 发布:淘宝游戏账号出售 编辑:程序博客网 时间:2024/05/22 11:48
/** * Index: 26 * Title: Remove Duplicates from Sorted Array * Author: ltree98 **/
题目给出的几个注意点:
1. 所给的数组是排序的(很重要)
2. 其实答案是根据返回的数组长度而截取原数组所得的数组
3. 空间复杂度在O(1)
记录重复数量,不重复的序列号,当前比较的数值
借助几个变量存储上述的值,在每次比较数值变化的时候,来改变序列号与比较数值,其他时候递增重复数值,即可。
class Solution {public: int removeDuplicates(vector<int>& nums) { int index = 0, cur = INT_MIN, repeat = 0, len = nums.size(); for(int i = 0; i < len; i++) { if(nums[i] > cur) { cur = nums[i]; nums[index++] = cur; } else ++repeat; } return len - repeat; }};
更为精简
只用一个变量,来存储重复的数量,
如果连续的两个数值不等,就将之前重复的替换掉(根据重复的数量可以求出)。
class Solution {public: int removeDuplicates(vector<int>& nums) { int repeat = 0, len = nums.size(); for(int i = 1; i < len; i++){ if(nums[i] == nums[i-1]) repeat++; else nums[i-repeat] = nums[i]; } return len-repeat; }};
0 0
- [Leetcode]_26 Remove Duplicates from Sorted Array
- [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
- A Beginner's Guide To Understanding Convolutional Neural Networks
- 小数据集训练深度网络的小技巧
- linux下php-fpm的启动和关闭
- 笔试时常用排序算法时间复杂度和空间复杂度
- A Beginner's Guide To Understanding Convolutional Neural Networks Part 2
- [Leetcode]_26 Remove Duplicates from Sorted Array
- Linux内核 printk知多少
- Oracle 11g通过提高IO吞吐量(修改_db_file_optimizer_read_count)来优化全表扫描
- Java基础-多线程的同步机制
- 最长公共子序列
- Buildings
- Codeforces Round #410
- Dagger2概念及使用
- s5pv210——LCD基础理论