LeetCode
来源:互联网 发布:信盈达 知乎 编辑:程序博客网 时间:2024/05/16 18:52
Q:
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.
A:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 pre = 0 for i in range(1, len(nums)): if nums[pre] != nums[i]: pre += 1 nums[pre] = nums[i] return pre + 1
注释:
从列表的第二个数(index=1)处开始遍历,与pre(初始为0)位置上的数进行比较,若相等,不做处理,继续;若不相等,则pre进一,将pre位置上的值更新;继续循环。
最后返回pre+1,即最终无重复数字列表的个数
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Java之String、StringBuffer、StringBuilder
- Ubuntu+anaconda环境里安装opencv
- JZOJ5360. 【NOIP2017提高A组模拟9.12】Shorten Diameter
- MITM arpspoof ARP 欺骗
- 超简单配置你的 oh my zsh
- LeetCode
- Maven中本地仓库,中央镜像,JDK版本配置
- jsp基础
- iOS 安装Nodejs环境自动打包
- 51nod 1007 正整数分组
- SPOJ NSUBSTR 后缀自动机+DP
- 互联网协议入门(二)
- java String一个字符串多次截取两个字符串之间的值
- ResultMap