027. Remove Element

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

給定一個(gè)數(shù)組和一個(gè)target,返回?cái)?shù)組中不等于target的元素個(gè)數(shù),并將不等于target的元素移動(dòng)到數(shù)組的前面。

public class Solution {
  public int removeElement(int[] nums, int val) {
    int length = 0;
    int end = nums.length - 1;
    int i = 0;
    while (i <= end) {
        if (nums[i] == val) {
            while (end > i && nums[end] == val) end--;
            if (end == i) break;
            nums[i] = nums[end];
            nums[end] = val;
        } else {
            length++;
            i++;
        }
    }
    return length;
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 9,934評(píng)論 0 23
  • 浪漫不是眼前的茍且, 詩(shī)的芬芳在遠(yuǎn)方的田野。 沒(méi)有情人日子不是世界的末日, 因?yàn)閻?ài)人才是整個(gè)的世界。 擁有了愛(ài)的日...
    琢玉書生閱讀 214評(píng)論 0 0
  • 如果你要去一個(gè)連地圖上都沒(méi)有標(biāo)注的地方,還要和幾個(gè)陌不相識(shí)的人相處幾個(gè)月,你會(huì)帶上什么? 這就是子思在發(fā)愁的問(wèn)題。...
    致一閱讀 299評(píng)論 0 0
  • 習(xí)慣幾
    倪20閱讀 166評(píng)論 0 0