对于数组移除元素,时间复杂度要求O(n),采用双指针方法

快指针:寻找新数组的元素,新数组就是不含有目标元素的数组

慢指针:指向更新 新数组下标的位置

完整代码如下:

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];
                slow++;
            }
        }
        //slow的大小就是新数组的右边界下标位置
        return slow;
    }
}

26.删除有序数组中的重复项

代码如下:

class Solution {
    public int removeDuplicates(int[] nums) {
        int slow = 0;
        for(int fast = 0; fast < nums.length; fast++){
            if(nums[fast] != nums[slow]){
                slow++;
                nums[slow] = nums[fast];
            }
        }
        return slow + 1;
    }
}

时间复杂度为O(n)

283.移动零

代码如下:

class Solution {
    public void moveZeroes(int[] nums) {
        int slow = 0;
        int count = 0;
        int n = nums.length - 1;
        for(int fast = 0; fast < nums.length; fast++){
            if(nums[fast] != 0){
                nums[slow] = nums[fast];
                slow++;
            }else{
                count++;
            }
        }

        for(int i = 0; i < count; i++){
            nums[n] = 0;
            n--;
        }

    }
}

时间复杂度为O(n)

844.比较含退格的字符串

使用栈的思想解决问题

代码如下:

class Solution {
    public boolean backspaceCompare(String s, String t) {
        
        if(build(s).equals(build(t))){
            return true;
        }else{
            return false;
        }
    }

    public String build(String str){

        StringBuilder ret = new StringBuilder();
        char[] strCharArray = str.toCharArray();
        for(int i = 0; i < strCharArray.length; i++){
            if(strCharArray[i] != '#'){
                ret.append(strCharArray[i]);
            }else{
                if(ret.length() > 0){
                    ret.deleteCharAt(ret.length() - 1);
                }
            }
        }
        return new String(ret);
    }
}

时间复杂度O(n)

977.有序数组的平方

双指针方法:构建一个新的数组。在原来的数组上构建两个指针,分别指向0和n-1的下标位置,每次比较这两个指针对应的数的平方的值,选择较大的那个逆序放入新的数组,并开始移动对应的左右指针,确定一个数后pos向前移动。

完整代码:

class Solution {
    public int[] sortedSquares(int[] nums) {
        //构建一个新的数组用来存放排序好的平方数组,大小与nums一致
        int[] sqrtNums = new int[nums.length];
        //pos指针表示从sqrtNums的最末尾开始插入数值,逆序
        for(int left = 0, right = nums.length - 1, pos = nums.length - 1; left <= right;){
            if(nums[left] * nums[left] > nums[right] * nums[right]){
                sqrtNums[pos] = nums[left] * nums[left];
                left++;
            }else{
                sqrtNums[pos] = nums[right] * nums[right];
                right--;
            }
            //确定下来一个数值后,pos向前移动
            pos--;
        }
        return sqrtNums;
    }
}

时间复杂度为O(n)

Categories:

Tags:

No responses yet

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注