LeetCode之Remove Duplicates from Sorted Array

举报
chenyu 发表于 2021/07/26 23:04:47 2021/07/26
【摘要】 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, y...

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.

 

2、实现

代码一实现:

   
  1. public class Solution {
  2. public int removeDuplicates(int[] a) {
  3. if (null == a) {
  4. return 0;
  5. }
  6. int length = a.length;
  7. // if (length > 0)
  8. // a[0] = a[0];
  9. int newLen = 1;
  10. for (int i = 1; i < length; ++i) {
  11. if (a[i] != a[i - 1]) {
  12. a[newLen++] = a[i];
  13. }
  14. }
  15. return newLen;
  16. }
  17. }

代码二实现:

   
  1. public int removeDuplicates1(int[] a) {
  2. if (a == null || a.length == 0) {
  3. return 0;
  4. }
  5. int length = a.length;
  6. for (int i = 0; i < length - 1; ++i) {
  7. if (a[i] == a[i + 1]) {
  8. for (int j = i + 1; j < length - 1; j++) {
  9. a[j] = a[j + 1];
  10. }
  11. i--;
  12. length--;
  13. }
  14. }
  15. return length;
  16. }

 
 


3、总结

方法一总结:我们不能重新申请空间,在原基础数组改,我们知道只要说到“连续数字”,我么应该马上想到这个数字和前面的数字相同,我们在原始数组上,第一个元素就是新数组的第一个元素,后面如果新元素和前面的元素不一样,我们就把这个后面的元素添加在新数组的末尾。
方法二总结:
记得进行i--和length--

文章来源: chenyu.blog.csdn.net,作者:chen.yu,版权归原作者所有,如需转载,请联系作者。

原文链接:chenyu.blog.csdn.net/article/details/66478068

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。