• [leetcode]26. Remove Duplicates from Sorted Array有序数组去重(单个元素只出现一次)


    Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

    Example 1:

    Given 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 returned length.

    Example 2:

    Given nums = [0,0,1,1,1,2,2,3,3,4],
    
    Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
    
    It doesn't matter what values are set beyond the returned length.

    题意:

    去除有序数组的重复元素,使得每个元素只能在数组中出现一次


    思路:

    仍然是在尽量不开新空间的情况下,

    直接在原数组中进行操作。

    指针i来遍历原数组。

    指针start 从 index 1 开始, 因为index 为 0 的元素是什么牛鬼蛇神都不重要。

    指针start 接受指针i扫过的、符合条件的元素。

    指针start 所到之处,便是新“数组”新生之时。


    代码:

     1 class Solution {
     2     public int removeDuplicates(int[] nums) {
     3         if(nums.length == 0) return 0;
     4         int start = 1;
     5         for(int i = 1; i < nums.length; i++){
     6             if(nums[i] != nums[start-1]){
     7                nums[start] = nums[i];
     8                start++;
     9             }
    10         }
    11       return start;  
    12     }
    13 }
  • 相关阅读:
    Activity和Service交互之bindService(回调更新UI)
    Service和Activity交互之广播方式
    自定义动态注册广播和静态注册广播
    Service
    AsyncTask
    播放视频
    播放音乐
    SurfaceView实现拍照预览
    从相册选取图片
    拍照并保存到指定文件夹
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9125439.html
Copyright © 2020-2023  润新知