leetCode练题——27. Remove Element
作者:互联网
1、题目
27. Remove Element——EasyGiven 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.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2, Your function should return length =5
, with the first five elements ofnums
containing0
,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.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy) int len = removeElement(nums, val); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
大致意思是把一个列表里指定的数字去掉,并且不新增存储空间,最后返回去除指定数字后的列表长度;
2、我的解法
还是采用双指针法,大致解法如下:
# -*- coding: utf-8 -*-
# @Time : 2020/2/3 15:38
# @Author : SmartCat0929
# @Email : 1027699719@qq.com
# @Link : https://github.com/SmartCat0929
# @Site :
# @File : 27. Remove Element.py
from typing import List
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
lens = len(nums)
if lens > 0: #判断列表是否为空
j = 0
for i in range(lens):
if nums[i] != val: #若i指定的数字不等于val
temp = nums[j]
nums[j] = nums[i]
nums[i] = temp #i和j指向的数字位置互换
j = j + 1 #j再往后移动
return j
print(Solution().removeElement([3,3,2],3))
标签:27,val,nums,int,length,练题,array,leetCode,elements 来源: https://www.cnblogs.com/Smart-Cat/p/12256751.html