5 lines C++/Java, nicer loops


  • 75

    I don't like old-style indexed looping. I much prefer the "enhanced" (Java) / "range-based" (C++) loops, they make things much cleaner.


    C++

    int removeDuplicates(vector<int>& nums) {
        int i = 0;
        for (int n : nums)
            if (!i || n > nums[i-1])
                nums[i++] = n;
        return i;
    }
    

    And to not need the !i check in the loop:

    int removeDuplicates(vector<int>& nums) {
        int i = !nums.empty();
        for (int n : nums)
            if (n > nums[i-1])
                nums[i++] = n;
        return i;
    }
    

    Java

    public int removeDuplicates(int[] nums) {
        int i = 0;
        for (int n : nums)
            if (i == 0 || n > nums[i-1])
                nums[i++] = n;
        return i;
    }
    

    And to not need the i == 0 check in the loop:

    public int removeDuplicates(int[] nums) {
        int i = nums.length > 0 ? 1 : 0;
        for (int n : nums)
            if (n > nums[i-1])
                nums[i++] = n;
        return i;
    }

  • -6
    S
    public class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length ==1)
            return 1;
        int cnt = 0;
        for(int i=0;i<nums.length;){
            nums[cnt++] = nums[i];
            while(i<nums.length-1 && nums[i]==nums[i+1]){
                i++;
            }
            
            i++;
        }
        return cnt;
    }
    

    }


  • 0
    B

    You sir are inspiration :)


  • 1
    X
    int i = !nums.empty();
    

    How can you come up with that,My GOD.


  • 0
    S

    Awesome! Elegant!


  • 0
    H

    good program,so nice


  • 0

    The Question doesn't say that the array is sorted in ascending order.
    Is it better to replace the '<' with '!='?


  • 0
    This post is deleted!

  • 0
    H

    Jesus!
    Your solution is so smart.


  • 0
    N

    I love this code


  • 0
    D

    why not using the following statement?

    n != nums[i-2]

Log in to reply
 

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