【LeetCode】27.Remove Element(Easy)解题报告

来源:互联网 发布:k歌之王65首歌名知乎 编辑:程序博客网 时间:2024/05/21 18:35

【LeetCode】27.Remove Element(Easy)解题报告

题目地址:https://leetcode.com/problems/remove-element/description/
题目描述:

  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 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:Given nums = [3,2,2,3], val = 3,Your function should return length = 2, with the first two elements of nums being 2.

  这道题开始不知道到底要求返回什么,但是题里显示返回int,应该是新长度len,但是返回新长度的同时,数组前len个元素也要存新数组的元素。两种方法。

Solution1:用的two pointer。我感觉精髓的地方就是调换元素之后,调换后还可能是val,但是这里他还会看是否相等,不等时begin才会++。

class Solution {    public int removeElement(int[] nums, int val) {        int begin=0,end=nums.length-1;        while(begin<=end){            if(nums[begin]==val){                nums[begin]=nums[end];                end--;            }else{                begin++;            }        }        return end+1;    }}

Solution2:既然不可以新开数组,肯定原数组存新信息。那么逛街在于if(nums[i]!=val)。

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

Date:2017年11月27日

原创粉丝点击