1. 程式人生 > >[LeetCode] 27. Remove Element

[LeetCode] 27. Remove Element

must 我不 value 個數 相等 什麽 att example 就是


Given an array nums and a value val, remove all instances of that value in-place and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

The order of elements can be changed. It doesn‘t matter what you leave beyond the new length.

Example 1:

Given nums = [3,2,2,3], val = 3,

Your function should return length = 2, with the first two elements of nums being 2.

It doesn‘t matter what you leave beyond the returned length.

Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

Your function should return length = 5, with the first five elements of nums
containing 0, 1, 3, 0, and 4. Note that the order of those five elements can be arbitrary. It doesn‘t matter what values are set beyond the returned length.

題意:從一個數組中刪除與val相應的元素,並返回刪除後的長度
先理解這裏的刪除,其實就是都放到隊尾
解法一:雙指針,頭換尾,尾的值是val就是往前移動,
class Solution {
    public int removeElement(int[] nums, int
val) { int sum = 0; int i = 0; int j = nums.length - 1; while (i <= j) { if (i == j) { if (nums[i] == val) sum ++; break; } if (nums[i] == val) { while (nums[j] == val) { j--;sum ++; if (j < 0) break; if (j == i) break; } if (j < 0) { break; } swap(nums, i, j); j --;sum++; } else { i ++; } } return nums.length - sum; } private void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } }

解法二:邊移動邊換
class Solution {
    public int removeElement(int[] nums, int val) {
        int j = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == val) {
                nums[j] = nums[i];
                j ++;
            }
        }
        return j;
    }
}

解法三:先排序,然後操作,因為排了序之後所有相同的val就都在一起了

(其實這裏我不是很能理解,為什麽這個O(nlogn)的算法確快了,這個代碼我是抄的,因為一直想著應該是O(n)的算法一開始就沒想過排序操作 (笑)

後來我又審查了我的代碼,可能在n比較小的時候,可能由於交換需要的代價比較大吧,)

class Solution {
    public int removeElement(int[] nums, int val) {
        
        Arrays.sort(nums);
        
        int result=0;//未與k重復元素的下標
            
        for(int i=0;i<nums.length;i++){

            if(nums[i]==val){
                
                //在數組中i之後找到第一個與k不相等的元素的下標
                i=noEqualsK(nums,i+1,val);
                for(;i<nums.length;i++){
                    
                    nums[result++]=nums[i];
                    
                }
                
            }else{
                
                result++;
                
            }
        }
        
        return result;

    }
    //返回數組中i之後找到第一個與k不相等的元素的下標
    public int noEqualsK(int[] nums,int i,int val){
        
        for(;i<nums.length;i++){

            if(nums[i]!=val){
                
                return i;
                
            }
        }
        
        return nums.length;
    }
    
}



[LeetCode] 27. Remove Element