leetcode27: Remove Element

来源:互联网 发布:商务推广软件 编辑:程序博客网 时间:2024/05/29 13:01
要求:

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.

简而言之:删掉数组中重复的元素,返回数组长度

注意:思路很简单,将需要删掉的元素放在数组尾部即可,时间复杂度应当是O(n)

附上通过的代码,非常简单

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

再附上我写的没通过的代码,思路是一样的,但是写的宛如智障一般,想了半天还没通过。放在这里以示警醒,不要把问题想的太复杂了。一开始还想用ArrayList,脑子进水了

public static int removeElement(int[] nums, int val) {int j = 0, count = 0;int l = nums.length;int i = 0;if(nums.length==0)return nums.length;if(nums.length==1&&nums[0]==val)return 0;if(nums.length==1&&nums[0]!=val)return 1;for (i = 0; i < l; i++) {if (nums[i] != val) {nums[j++] = nums[i];++count;}}return l - count;}




0 0
原创粉丝点击