27. Remove Element

来源:互联网 发布:中国 改革开放 知乎 编辑:程序博客网 时间:2024/05/17 07:02

Given an array and a value, 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 in place with constant memory.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

Example:
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.


题目主要意思:给你一个数组和一个数字,返回将数组中与数字相同的部分去掉后的长度len,以及这个数组的前len位是与数字不相同的部分

 自己做,如下所示:
public static int removeElement(int[] nums, int val) {
        int count = 0;
        int len = nums.length;
        if(len == 0 || nums == null){
         return 0;
        }
       
        Arrays.sort(nums);
        for(int i = 0; i < len ; i++){
         if(nums[i] == val){
          count++;
          nums[i] = nums[len-count];
         }else if(count > 0)
          break ;
        }
        return len - count;
}

提交后看到别人写的,如下所示:
 public static int removeElement(int[] nums, int val) {
       int count = 0;
       int len = nums.length;
       if(len == 0 || nums == null){
        return 0;
       }
       for(int i = 0;i < len ;i++){
        if(nums[i] != val){
         nums[count++] = nums[i];
        }
       }
       return count;
    }
原创粉丝点击