Leet -- Remove Duplicates from Sorted Array
来源:互联网 发布:2017nba总决赛球员数据 编辑:程序博客网 时间:2024/05/21 08:48
题目描述:
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.
就是在不使用额外空间的情况下,直接修改nums数组,移除重复元素,返回新长度。
思路:
使用两个变量:
front 用于遍历nums数组,从下标0开始,一直往前走
now 仅当nums[now]与nums[front]不等时,now+1,并把nums[now]=nums[front]
最后返回nums[now+1]
实现代码:
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.
就是在不使用额外空间的情况下,直接修改nums数组,移除重复元素,返回新长度。
思路:
使用两个变量:
front 用于遍历nums数组,从下标0开始,一直往前走
now 仅当nums[now]与nums[front]不等时,now+1,并把nums[now]=nums[front]
最后返回nums[now+1]
实现代码:
public class Solution { public int RemoveDuplicates(int[] nums) { if(nums == null || nums.Length == 0){return 0;}int now = 0;int front = 1;for(;front < nums.Length; ){if(nums[now] != nums[front]){now ++;nums[now] = nums[front];}front++;}return now + 1; }}
0 0
- [leet code] Remove Duplicates from Sorted Array
- Leet -- Remove Duplicates from Sorted Array
- [leet code] Remove Duplicates from Sorted Array I & II
- 【Leet Code】26. Remove Duplicates from Sorted Array---Easy
- 【Leet Code】80. Remove Duplicates from Sorted Array II---Medium
- 【LEET-CODE】26. Remove Duplicates from Sorted Array
- [leet code] Remove Duplicates from Sorted List
- leet code 第25-26题Remove Duplicates from Sorted Array & Remove Element
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates From Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- leetCode 115.Distinct Subsequences(子序列距离) 解题思路和方法
- 基于Spring的Web缓存
- Socket 通信原理(Android客户端和服务器以TCP&&UDP方式互通)
- SSL与TLS的区别以及介绍
- 细说 iOS 消息推送
- Leet -- Remove Duplicates from Sorted Array
- 图解SSL/TLS协议
- 大数模板——参考《入门经典》
- Victor and Machine
- 部署Spring Boot应用
- PHP PDO 安全执行 set names utf8 的正确方法
- Oracle数据库迁移MySql
- Java关键字(基础学习用到)
- 了解自己的路线