27. Remove Element

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.

Solution:

看了提示說用two pointer,沒有思路,參考discuss:
兩個指針 i 和 j,其中i用來遍歷數(shù)組,j用來記錄下一個可以放置元素的位置,整體思路是遍歷數(shù)組,如果元素不等于目標val,則保留,將其放在下一個可以放置元素的位置。如果相等則不做任何動作(這樣j指針就沒有更新,一直指向等于val的那個元素,則下次出現(xiàn)不等于val的元素時,那個元素就會被放在j指針指向的位置,與val相等的元素就被覆蓋)

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];
                j ++;
            }
        }
        return j; // j get increased in the last iteration, so now its value is the length of the array
    }
}
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容