Leetcode27--->Remove Element(移除数组中给定元素)

时间:2021-08-21 03:42:29

题目:给定一个数组array和一个值value,移除掉数组中所有与value值相等的元素,返回新的数组的长度;要求:不能分配额外的数组空间,且必须使用原地排序的思想,空间复杂度O(1);

举例:

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

Your function should return length = 2, with the first two elements of nums being 2.

解题思路:

1.  首先找到第一个等于value和第一个不等于value的数的位置;

2.  等于value和不等于value之间的数则全部为value;

3.  每次交换时一定是第一个等于value和第一个不等于value的数进行交换;

举例说明:

3,3,3,2,2,3,1,2,4,3,4,3,2 ;  value = 3

1) 初始时:start = 0; index = 3; exchange两个位置的数,结果变为:2,3,3,3,2,3,1,2,4,3,4,3,2;

2) start = 1; index = 4; exchange: 2,2, 3,3,3,3,1,2,4,3,4,3,2;

3) start = 2; index = 5;因为nums[index] = 3,因此index一直递增,直到nums[index] != 3,此时index = 6; exchange: 2,2, 1,3,3,3,3,2,4,3,4,3,2;

4) start = 3; index = 7;exchange: 2,2, 1,2,3,3,3,3,4,3,4,3,2;

5) start = 4; index = 8; exchange: 2,2, 1,2,4,3,3,3,3,3,4,3,2;

6) start = 5; index = 9; nums[index] = 3, index递增,直到index = 10:exchange: 2,2, 1,2,4,4,3,3,3,3,3,3,2;

7) start = 6; index = 11; nums[index] = 3, index递增,直到index = 12: exchange: 2,2, 1,2,4,4,2,3,3,3,3,3,3;

此时start = 7;index = 12 等于数组长度,结束;

代码如下:

 public class Solution {
public int removeElement(int[] nums, int val) {
if(nums == null || nums.length < 1){
return 0;
}
int count = 0;
int index = 0;
while(index < nums.length && nums[index] != val){index ++; count ++;} //找到第一个等于value的数
int start = index;
while(index < nums.length && nums[index] == val){index ++;} //找到第一个不等于value的数
while(start < nums.length && index < nums.length){
exchange(nums, start, index);
count ++;
start ++;
while(index < nums.length && nums[index] == val){index ++;} }
return count;
}
public static void exchange(int[] nums, int index1, int index2)
{
int temp = nums[index1];
nums[index1] = nums[index2];
nums[index2] = temp;
}
}