首页 > 代码库 > Leetcode27--->Remove Element(移除数组中给定元素)

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

题目:给定一个数组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 = http://www.mamicode.com/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 等于数组长度,结束;

代码如下:

 1 public class Solution { 2     public int removeElement(int[] nums, int val) { 3         if(nums == null || nums.length < 1){ 4                 return 0; 5         } 6         int count = 0; 7         int index = 0; 8         while(index < nums.length && nums[index] != val){index ++; count ++;}  //找到第一个等于value的数 9         int start = index;10         while(index < nums.length && nums[index] == val){index ++;}  //找到第一个不等于value的数11         while(start < nums.length && index < nums.length){12             exchange(nums, start, index);13             count ++;14             start ++;15             while(index < nums.length && nums[index] == val){index ++;}16 17         }18         return count;19     }20      public static void exchange(int[] nums, int index1, int index2)21      {22         int temp = nums[index1];23         nums[index1] = nums[index2];24         nums[index2] = temp;25      }26 }

 

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