【Leetcode】100. Remove Duplicates from Sorted Array

100. Remove Duplicates from Sorted Array

Description

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.

Example

Given input array A = [1,1,2],

Your function should return length = 2, and A is now [1,2].

Solution

idea:从数组开头到 nums[i] 的所有数均为不重复的数。

i 从 0 开始(第一个数),若遇到一个和第一个数不一样的数(即第二个数),则将 i 进一位并将 nums[i] 赋值为第二个数,依次类推,直到数组最后一个数。因此,共有 i+1 个数是不重复的数。

public class Solution {
    /**
     * @param A: a array of integers
     * @return : return an integer
     */
    public int removeDuplicates(int[] nums) {
        // write your code here
        if(nums == null || nums.length == 0){
            return 0;
        }

        int i = 0;
        for(int j = 1; j < nums.length; j++){
            if(nums[j] != nums[i]){
                i++;
                nums[i] = nums[j];
            }
        }

        return i + 1;
    }
}

Follwup Question

Follow up for “Remove Duplicates”:

What if duplicates are allowed at most twice?

For example,

Given sorted array A = [1,1,1,2,2,3],

Your function should return length = 5, and A is now [1,1,2,2,3].

Solution

额外用一个 boolean 表示是否可以添加重复元素,只有 boolean 为 true 时才能添加重复元素。当添加一个新元素时,boolean 设置为 true,当添加一个重复元素后,boolean 设置为 false。

public class Solution {
   /**
    * @param A: a array of integers
    * @return : return an integer
    */
   public int removeDuplicates(int[] nums) {
       // write your code here
       if(nums == null || nums.length == 0){
           return 0;
       }

       boolean twice = true;
       int i = 0;
       for(int j = 1; j < nums.length; j++){
           if(nums[j] != nums[i]){
               i++;
               nums[i] = nums[j];
               twice = true;
           }else if(twice){
               i++;
               nums[i] = nums[j];
               twice = false;
           }
       }
       return i + 1;
   }
}
发布了42 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/WBST5/article/details/105505137