(算法分析Week9)Remove Duplicates from Sorted Array[Easy]
来源:互联网 发布:java math.random用法 编辑:程序博客网 时间:2024/05/18 23:25
26. Remove Duplicates from Sorted Array[Easy]
题目来源
Description
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 by modifying the input array in-place with O(1) extra memory.
Example:
Given 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
一个水题放松一下。
一个已经排好序的数组,删除重复元素,即只用和自己左边的数比较就好。
不允许用额外的空间,否则直接new一个数组存数。
我用的方法是从第二个元素(下标为1)开始,数重复个数长度(length),直到第一个和先前不重复的元素出现,插在(i-length)的位置,就是说到目前为止有i个元素,其中length个是重复的,那i-length就是第一个重复的元素位置。不停循环,最后返回处理后的数组长度。
Complexity analysis
O(n)
Code
class Solution {public: int removeDuplicates(vector<int>& nums) { int length = 0; for (int i = 1; i < nums.size(); i++) { if (nums[i] == nums[i-1]) { length++; } else { nums[i - length] = nums[i]; } } return nums.size() - length; }};
Result
阅读全文
0 0
- (算法分析Week9)Remove Duplicates from Sorted Array[Easy]
- 26. Remove Duplicates from Sorted Array [easy]
- 【Easy】26. Remove Duplicates from Sorted Array
- leetcode26[easy]--- Remove Duplicates from Sorted Array
- [LeetCode] 026. Remove Duplicates from Sorted Array (Easy) (C++/Java)
- [Leetcode 26, easy] Remove Duplicates from Sorted Array
- 【Leet Code】26. Remove Duplicates from Sorted Array---Easy
- Easy-题目29:26. Remove Duplicates from Sorted Array
- 26. Remove Duplicates from Sorted Array [easy] (Python)
- Leetcode 26. Remove Duplicates from Sorted Array (Easy) (cpp)
- Leetcode 26. Remove Duplicates from Sorted Array (Easy) (java)
- Easy 7 Remove Duplicates from Sorted Array(26)
- 26. Remove Duplicates from Sorted Array(easy)
- LeetCode-Easy刷题(7) Remove Duplicates from Sorted Array
- LeetCode---Remove Duplicates from Sorted Array、Remove Duplicates from Sorted Array II解题分析
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- 背包问题之01背包
- markdown入门指南
- elasticsearch index and store
- 在网页下载特定的table的对应处理
- css和dos
- (算法分析Week9)Remove Duplicates from Sorted Array[Easy]
- java 之 Properties集合
- 园
- jsp 写一个cookie
- 理解大型分布式网站必须知道这些概念
- docker hub切换国内镜像
- 设计模式(11)——享元 Flyweight
- 从零开发微信公众号系列 【二】开发者基本配置和接入指南
- thinkphp 检测上传的图片中是否含有木马脚本