LeetCode之Remove Duplicates from Sorted Array

简介: LeetCode之Remove Duplicates from Sorted Array

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、实现

代码一实现:

public class Solution {
    public int removeDuplicates(int[] a) {
        if (null == a) {
        return 0;
      }
      int length = a.length;
     // if (length > 0)
     // a[0] = a[0];
      int newLen = 1;
      for (int i = 1; i < length; ++i) {
        if (a[i] != a[i - 1]) {
          a[newLen++] = a[i];
        }
      }
      return newLen;
    }
}

代码二实现:

public  int removeDuplicates1(int[] a) {
    if (a == null || a.length == 0) {
      return 0;
    }
        int length = a.length;
    for (int i = 0; i < length - 1; ++i) {
      if (a[i] == a[i + 1]) {
        for (int j = i + 1; j < length - 1; j++) {
          a[j] = a[j + 1];
        }
        i--;
        length--;
      }
    }
    return length;
  }

3、总结

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

方法二总结:

记得进行i--和length--

相关文章
|
8月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
19 0
|
8月前
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
28 0
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
55 0
LeetCode 167 Two Sum II - Input array is sorted(输入已排序数组,求其中两个数的和等于给定的数)
给定一个有序数组和一个目标值 找出数组中两个成员,两者之和为目标值,并顺序输出
66 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
23天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
23天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
24天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
|
24天前
|
算法
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)
【LeetCode刷题】滑动窗口解决问题:串联所有单词的子串(困难)、最小覆盖子串(困难)