leetcode26. Remove Duplicates from Sorted Array
来源:互联网 发布:python股票大数据分析 编辑:程序博客网 时间:2024/06/06 04:14
题目
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.
思路
用两个指针,一个指针f指向上一个,一个指针s指向下一个。如果f的值小于s的值,则计数。
代码
public class Solution { public int removeDuplicates(int[] nums) { if(nums.length <=1){ return nums.length; } int count = 1, index = 1; for( int i = 1; i < nums.length; ){ if(nums[i-1] < nums[i]){ count++; nums[index] = nums[i]; index ++; i++; } else{ while(i < nums.length && nums[i - 1] == nums[i]) i++; } } return count; }}
结果
他山之玉
public int removeDuplicates(int[] nums) { int i = nums.length > 0 ? 1 : 0; for (int n : nums) if (n > nums[i-1]) nums[i++] = n; return i;}
class Solution { public: int removeDuplicates(int A[], int n) { if(n < 2) return n; int id = 1; for(int i = 1; i < n; ++i) if(A[i] != A[i-1]) A[id++] = A[i]; return id; }};
from collections import OrderedDictclass Solution(object): def removeDuplicates(self, nums): nums[:] = OrderedDict.fromkeys(nums).keys() return len(nums)
阅读全文
0 0
- leetcode26. [Array]Remove Duplicates from Sorted Array
- [LeetCode26]Remove Duplicates from Sorted Array
- Leetcode26-Remove Duplicates from Sorted Array
- LeetCode26:Remove Duplicates from Sorted Array
- Leetcode26 Remove Duplicates from Sorted Array
- leetCode26:Remove Duplicates from Sorted Array
- leetcode26:Remove Duplicates from Sorted Array
- leetcode26. Remove Duplicates from Sorted Array
- [LeetCode26] Remove Duplicates from Sorted Array
- LeetCode26. Remove Duplicates from Sorted Array
- [leetcode26] Remove Duplicates from Sorted Array
- Leetcode26. Remove Duplicates from Sorted Array
- Leetcode26. Remove Duplicates from Sorted Array
- LeetCode26. Remove Duplicates from Sorted Array
- leetcode26:Remove Duplicates from Sorted Array
- leetcode26. Remove Duplicates from Sorted Array
- leetcode26~Remove Duplicates from Sorted Array
- leetcode26. Remove Duplicates from Sorted Array
- 在win32 安装matplotlib,numpy遇到的问题及解决
- 版本管理工具——git
- 搭建python+openCV环境
- 三句话总结JAVA泛型通配符(PECS)
- jquery.min.js multiple markers at this line
- leetcode26. Remove Duplicates from Sorted Array
- Android SQLite使用
- ThreadLocal源码及存在的内存泄漏分析
- 数据库连接出现乱码问题
- servlet的异步处理支持
- Swift: Xcode 真机调试
- mysleep 的两种实现
- 困难得有点不正常
- 为什么一个网站的资源会存在于多个域名中?