[LeetCode][Java] Remove Duplicates from Sorted Array
来源:互联网 发布:淘宝怎么看卖家信誉 编辑:程序博客网 时间:2024/05/02 00:43
题目:
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 = [1,1,2]
,
你所写的函数需要返回长度2,数组中的两个元素分别为1
and 2。
数组中的超过这个长度的元素无关紧要。
算法分析:
利用双指针
* 前后两个指针,前指针固定不动,后指针去搜索
* 直到后指针指到与前指针不同的元素上,这时统计到了第二个不同元素,i++;
* 前指针重置到现在后指针的位置
* 重复上述过程,能够统计出不同的元素的总个数,而且原数组中的前i个元素即为这i个互为不同的元素
AC代码:
/** * 前后两个指针,前指针固定不动,后指针去搜索 * 直到后指针指到与前指针不同的元素上,这时统计到了第二个不同元素,i++; * 前指针重置到现在后指针的位置 * 重复上述过程,能够统计出不同的元素的总个数,而且原数组中的前i个元素即为这i个互为不同的元素 */ public class Solution { public int removeDuplicates(int[] nums) {if(nums.length==0) return 0;int startindex = 0;int endindex = 0;int i=0; while(endindex<nums.length) { while(endindex<nums.length) { if(nums[startindex]==nums[endindex]) endindex++; else { break; } } nums[i]= nums[startindex];startindex=endindex;i++; }return i; }}
- [Leetcode] Remove Duplicates from Sorted Array (Java)
- [LeetCode][Java] Remove Duplicates from Sorted Array
- 【leetcode】Remove Duplicates from Sorted Array【java】
- leetcode:Remove Duplicates from Sorted Array 【Java】
- LeetCode : Remove Duplicates from Sorted Array [java]
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array II (Java)
- LeetCode – Remove Duplicates from Sorted Array (Java)
- LeetCode – Remove Duplicates from Sorted Array II (Java)
- LeetCode – Remove Duplicates from Sorted Array (Java)
- 【Leetcode】Remove Duplicates from Sorted Array in JAVA
- [LeetCode] 026. Remove Duplicates from Sorted Array (Easy) (C++/Java)
- Remove Duplicates from Sorted Array---leetcode 我的java题解
- LeetCode(026) Remove Duplicates from Sorted Array (Java)
- LeetCode(080) Remove Duplicates from Sorted Array II (Java)
- [LeetCode][Java] Remove Duplicates from Sorted Array II
- LeetCode 26 : Remove Duplicates from Sorted Array (Java)
- Groovy数据类型
- Linux : chkconfig
- MySQL的触发器创建之注意事项(有关delimiter)
- "数字签名"(digital signature)和"数字证书"(digital certificate)
- Java的安全学习(包括加密,数字签名,证书和认证)
- [LeetCode][Java] Remove Duplicates from Sorted Array
- 翻转
- iOS网络协议----HTTP/TCP/IP浅析
- 树莓派自动登陆
- 转载邮件失败!javax.mail.AuthenticationFailedException: 535 Error: authentication
- Android 自己动手编译android源码
- B树、红黑树简单概念
- C语言 printf
- java底层的深入理解——————堆栈