[LeetCode]第七题 :去掉重复值

题目描述:

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.

题目解释:

给出一个数组和一个值,去掉数组中所有等于这个值的数字。不得使用额外的数组,空间复杂度必须为1。这个数组的元素顺序可以改变,并且返回数组的长度就行。

题目解法:

1.我的解法:类似于冒泡,需要一个下标当工作指针,倒序遍历这个数组,遇到第一个指定数字的时候把它放到末尾,遇到第二个指定数字的时候放到倒数第二位,直到最后遍历完,返回工作指针+1即新数组的长度。

class Solution {
    public int removeElement(int[] nums, int val) {
        int index = nums.length - 1;
        for(int i = nums.length - 1; i >= 0; i--) {
            if(nums[i] == val) {
                int temp = nums[index];
                nums[index] = nums[i];
                nums[i] = temp;
                index--;
            }
        }
        return index + 1;
    }
}

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80805813