leetcode 27: removing elements

problem:

Given an array nums and a value val, you need to place the elements to remove all equal values ​​val, and returns the new length of the array after removal.

Do not use extra space for an array, you must modify the input array in place and completed under the conditions of use O (1) extra space.

Order of the elements may be changed. You do not need to consider beyond the elements of the new array length behind.

Example 1:

Given nums = [3,2,2,3], val = 3,

Function should return a new length of 2, and the first two elements nums are 2.

You do not need to consider beyond the elements of the new array length behind.
Example 2:

Given nums = [0,1,2,2,3,0,4,2], val = 2,

New function should return the length 5 and the first five elements nums is 0, 1, 3, 0, 4.

Note that these five elements can be in any order.

You do not need to consider beyond the elements of the new array length behind.

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/remove-element

answer 1:

Two pointers i and j, i is initialized to 0, j to len - 1, i moved backward, j is moved forward, when the nums [i] is equal to val, exchange points i and j values.

To prevent nums [j] is also equal to val, when nums [j] is equal to val, J constantly decremented until no equal val.

 1 class Solution:
 2     def removeElement(self, nums: List[int], val: int) -> int:
 3         nums_len = len(nums)
 4         if nums_len == 0:
 5             return 0
 6         i = 0
 7         j = nums_len - 1
 8         while i < j:
 9             if nums[j] == val:
10                 j -= 1
11                 continue
12             if nums[i] == val:
13                 t = nums[i]
14                 nums[i] = nums[j]
15                 nums[j] = t
16                 j -= 1
17             i += 1
18         if nums[j] == val:
19             j -= 1
20         return j + 1

 

answer 2:

See other people submitted discovered a simpler method,

Let k is initialized to 0, the end point of a new array is known.

Traverse the old array, when an element is not equal to val, that is, the element is an element of the new array, let nums [k] is equal to the elements, and let k plus one.

1 class Solution:
2     def removeElement(self, nums: List[int], val: int) -> int:
3         nums_len = len(nums)
4         k = 0
5         for num in nums:
6             if num != val:
7                 nums[k] = num
8                 k += 1
9         return k

 

Guess you like

Origin www.cnblogs.com/lxc1910/p/11367539.html