27. Remove Element-Easy-Array

Problem

Given an array nums and a value val, remove all instances of that value in-placeand 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 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.

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]);
}

Tag

two-pointers

Relative background knowledge

“凡是数组的题目,大部分都是利用双指针去解决问题。”

双指针,顾名思义,就是利用两个指针去遍历数组,一般来说,遍历数组采用的是单指针(index)去遍历,两个指针一般是在有序数组中使用,一个放首,一个放尾,同时向中间遍历,直到两个指针相交,完成遍历,时间复杂度也是O(n)。

用法

一般会有两个指针front,tail。分别指向开始和结束位置。

  front = 0;
  tail = A.length()-1

一般循环结束条件采用的是判断两指针是否相遇

  while(fron < tail)
  {
  ……
  }

对于in place交换的问题,循环结束条件一般就是其中一个指针遍历完成。

使用范围

一般双指针在有序数组中使用的特别多。(部分情况下,未排序数组也有应用) 一般用来解决下列问题(陆续补充中):

1. 两数求和

一般这种问题是问,寻找两个数的和为一个特定的值(比如后面的N SUM问题),这时候,如果数组有序,我们采用两个指针,分别从前和后往中间遍历,front移动和增大,tail移动和减小,通过特定的判断,可以求出特定的和。时间复杂度为O(n),如果用双重循环则要O(n^2)。

2. in place交换

数组的in place(就地)交换一般得用双指针,不然数组中添加或删除一个元素,需要移动大量元素。

这时候,一般是一个指针遍历,一个指针去找可以用来交换的元素。

 

Solution

It depends on whether val is rare in the array.

1. If val is not rare:

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

2. If val is rare:

The pointer starts from the tail to the head.

Complexity

time complexity:O(n)

space complexity:O(1)

猜你喜欢

转载自www.cnblogs.com/cecilia-xu/p/10352512.html