LeetCode 27. Remove Element

17 篇文章 0 订阅
15 篇文章 0 订阅

官方提示( C l a r i f i c a t i o n Clarification Clarification)真的具有误导作用,真要看还得看 E x a m p l e Example Example

Example 1:

Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2]
Explanation: 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. For example if you return 2 with nums = 
[2,2,3,3] or nums = [2,3,0,0], your answer will be accepted.

Example 2:

Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3]
Explanation: 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.

与 LeetCode 26. Remove Duplicates from Sorted Array 不同的是
本题修改完元素位置后的数组,前面几个元素不一定要按照特定顺序排序

举个例子(用下面JAVA的两种方法打印修改后的数组)

int[] nums = new int[]{1,2,3,3,3,4,5,6};			// 原数组

System.out.println(test.removeElement(nums,3));		// 数组按顺序
System.out.println(test2.removeElement(nums,3));	// 数组不按顺序

// 打印数组
output:
[1, 2, 4, 5, 6]
[1, 2, 6, 5, 4]

JAVA

① 数组按顺序(快指针和慢指针)

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

② 数组不按顺序(双指针)

class Solution {
    public int removeElement(int[] nums, int val) {
        int i = 0;
        int n = nums.length;		// 之所以不用 n = nums.length-1
        while (i < n) {				// 是因为 while循环要模仿 for循环迭代到 nums.length
            if (nums[i] == val) {
                nums[i] = nums[n - 1];
                n--;
            } else {
                i++;
            }
        }
        return n;
    }
}

Python

① 数组按顺序(快指针和慢指针)

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0
        for j in range(len(nums)):
            if(nums[j] != val):
                nums[i] = nums[j]
                i+=1
        return i

② 数组不按顺序(双指针)

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        i = 0
        j = len(nums)
        while i < j:
            if(nums[i] == val):
                nums[i] = nums[j-1]
                j -= 1
            else:
                i += 1
        return i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值