LeetCode-27:移除元素

74 阅读1分钟

题目链接:https://leetcode.cn/problems/binary-search/ image.png

方法一:

暴力求解方法:思想就是移动数组覆盖等于val 的值

public int removeElement(int[] nums, int val) {
    	//for循环i的范围,应该用size,不能用nums.length,
        //因为下面 i--,size --;nums.length是动态的,
        //所以用size变量接受nums.length定值。
        int size = nums.length; 
        for(int i = 0 ;i<size;i++){
            if(nums[i]==val){
                for(int j = i+1;j<size;j++){
                    nums[j-1] = nums[j];
                }
                i--;//覆盖后 原来数组减小
                size--;//数组总长度减小
            }
        }
        return size;
    }

方法二:

双指针方法---用快慢指针:通过一个快指针和慢指针在一个for循环下完成两个for循环的工作。

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public int removeElement(int[] nums, int val) {
        int slow = 0;
        for(int fast = 0;fast<nums.length;fast++){
            if (nums[fast] != val){
                nums[slow++] = nums[fast];
            }
        }
        return slow;
    }
}
//leetcode submit region end(Prohibit modification and deletion)