Two easy java solution


  • 0

    version 1:

    public class Solution {
        public int removeDuplicates(int[] nums) {
           int n = nums.length;
           if(n<=1) return n;
           
           int idx = 0;
           for(int i=1;i<n;++i){
               if(nums[i] != nums[idx]){
                   nums[++idx] = nums[i];
               }
           }
           
           return idx+1;
        }
    }
    
    

    Version 2:

    public int removeDuplicates(int[] nums) {
           int n = nums.length;
           if(n<=1) return n;
           
           int idx=1, i=1;
           while(i<n){
               while(i<n && nums[i] == nums[i-1]){
                   i++;
               }
               if(i==n) break;
               nums[idx++] = nums[i];
               i++;
           }
           
           return idx;
        }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.