记录七——移除元素

移除元素

题:给出一个数组nums和一个值val,移除数组中包含有val值得元素,返回新数组的长度。(注:不分配额外的数组空间,且通过O(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.


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值相等的元素进行标记,将其置为-1,第二步,将这些进行标记的位置已到数组的最后面,完成操作。但是这样的做法并不符合题意,虽然被接受了,但是空间复杂度超过了O(1),且这样做的前提是数组中不包含值为-1的元素。
代码:

class Solution {
    public int removeElement(int[] nums, int val) {
        int len = 0;
		for(int i = 0; i < nums.length; i++) {
			if(nums[i] == val) {
				nums[i] = -1;
			}
		}
		
		for(int i = 0;i < nums.length - 1;i++) {
			if(nums[i] == -1) {
				for(int j = i; j < nums.length - 1; j++) {
					int temp = nums[j];
					nums[j] = nums[j+1];
					nums[j+1] = temp;
				}
				
			}
		}
		for(int i = 0;i < nums.length - 1;i++) {
			if(nums[i] == -1) {
				for(int j = i; j < nums.length - 1; j++) {
					int temp = nums[j];
					nums[j] = nums[j+1];
					nums[j+1] = temp;
				}
				
			}
		}
		
		for(int i = 0;i < nums.length;i++) {
			if(nums[i] != -1) {
				len++;
			}
			//break;
		}
		return len;
    }
}

后序更新记录
看了解析,都是利用两个指针,第一种方法和记录十一的双指针是一样的原理,不再沾上源码。
题中说了,数组中的元素顺序是可变的,因此只要将目标元素val从数组中删除即可达到目的。如何达到删除的目的呢,首先觉得自己的想法是正确的,将数组中的目标元素移到数组的最后面,但将其设置为-1是不可取的。因此也是利用双指针,点睛之笔是利用指针来减小数组的大小,使得没有了重复无效的遍历。

class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        int n = nums.length;
        while(i < n) {
            if(nums[i] == val) {
                nums[i] = nums[n - 1];
                n--;
            }
            else{
                i++;
            }
        }
        return n;
    }
}

时间复杂度:O(n),空间复杂度:O(1)

猜你喜欢

转载自blog.csdn.net/w1375834506/article/details/88412520