27. Remove Element

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

5/26/2018 update:
第三遍虽然一开始没有思路,但是稍微想了一下就出来了。其实不用交换,直接赋值。
j++过后又2种情况。
1. nums[j] == nums[i]
2. nums[j] == nums[j - 1] 重复

           12223
 index j
            i

这是第一种情况, j++ 过后是1, nums[i] == nums[j] == 2.

           12223
 index   j
                    i
第二种起情况, j++ 过后是2, nums[j] == nums[j-1], nums[j]在这里是重复的,可以覆盖。
Analysis:
注意审题啊,这道题不仅要记录非重复的个数,而且要数组前排非重复。
Two pointers, i and j, j iterates from 0 to nums.length - 1. i increment if nums[j] != nums[i]. That is satisfy the none duplicate condition.

Solution:


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

评论

此博客中的热门博文

663. Equal Tree Partition

776. Split BST

426. Convert Binary Search Tree to Sored Doubly Linked List