LeetCode-Delete duplicates and remove elements in a sorted array (26 questions and 27 questions)

Let me start with some simple questions to increase my confidence.

26, delete duplicates in the sorted array

Title description:

Given a sorted array, you need to delete the repeated elements in place, so that each element only appears once, and return the new length of the removed array.

Don't use extra array space, you must modify the input array in place and use O(1) extra space.

class Solution {
    public int removeDuplicates(int[] nums) {
        int len = nums.length-1;
        int i=0;
        while(i<len){
            if(nums[i]==nums[i+1]){

                //移位的过程
                for(int j=i;j<len;j++){
                    nums[j]=nums[j+1];
                }
                i=0;
                len--;
            } else{
                i++;
            }
        }
        return len+1;
    }
}

27, remove elements

Title description:

Given an array of nums and a value of val, you need to remove all the elements whose value is equal to val in place, and return the new length of the removed array.

Don't use extra array space, you must only use O(1) extra space and modify the input array in-situ.

The order of the elements can be changed. You don't need to consider the elements in the array beyond the new length.

class Solution {
    public int removeElement(int[] nums, int val) {
        if(nums==null || nums.length==0){
            return 0;
        }
        int len = nums.length-1;
        int count=0;
        int i=0;
        while(i<len+1){
            if(val==nums[i]){
                //移除元素
                for(int j=i;j<len;j++){
                    nums[j]=nums[j+1];
                }
                i=0;
                len--;
                //表示移了多少次
                count++;
            } else{
                i++;
            }
        }
        return nums.length-count;
    }
}

 

Guess you like

Origin blog.csdn.net/kidchildcsdn/article/details/114226572