【LeetCode】Remove Element 解题报告

Remove Element

[LeetCode]

https://leetcode.com/problems/remove-element/

Total Accepted: 115693 Total Submissions: 341766 Difficulty: Easy

Question

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.

Ways

学学经验。需要一个新的数组,但是返回值是数组的长度,这个数组的长度意思是在原来的数组中从前面数有长是需要的。也就是说在原来的基础上截取多长一部分。

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

AC:1ms

Date

2016/5/3 11:29:08

你可能感兴趣的:(LeetCode)