Java, 0ms, least move ,with commnet


  • 0
    S
    //两个指针,一个在头一个在尾巴
    //从头到尾扫描,遇到value的就用尾巴的非val值替换。
    public static int removeElement(int[] nums, int val) {
    
        int valSize = 0;
        int rear = nums.length - 1;
    
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val) {
                //(get the last rear value!=val),cover the current val;
                //last move
                for (; rear != i && rear>=0; rear--) {
                    if (nums[rear] != val) {
                        nums[i] = nums[rear];
                        rear--;
                        break;
                    }
                }
                
                valSize++;
            }
        }
        return nums.length - valSize;
    }

Log in to reply
 

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