LeetCode:Remove Element

題目連接html

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.code


題目的意思是把數組中和給定的目標數字不一樣的元素,所有放到數組的前部htm

遍歷數組,若是在當前位置 i 碰到元素等於給定的目標數字,從數組尾部找一個不等於目標的數字,放到 i 位置blog

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int k = n-1;
        for(int i = 0; i <= k; i++)
            if(A[i] == elem)
            {
                while(k > i && A[k] == elem)k--;//從後面找到第一個不是elem的元素
                if(k == i)return i;
                else A[i] = A[k--];//k位置非elem的元素放到i位置
            }
        return k+1;
    }
};

 

其實遍歷找到等於目標數字的元素後,只須要把數組尾部元素放到當前位置,無論尾部元素是否爲目標數字            本文地址ip

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int k = n-1;
        for(int i = 0; i <= k;)
            if(A[i] == elem)
                A[i] = A[k--];//尾部元素放在當前位置
            else i++;
        return k+1;
    }
};

 

還有一種思路是把不等於目標數字的元素依次放到首部,若是不等於目標數字的元素較少,這種方法效率更高element

class Solution {
public:
    int removeElement(int A[], int n, int elem) {
        int k = 0;
        for(int i = 0; i < n; i++)
            if(A[i] != elem)A[k++] = A[i];
        return k;
    }
};

 

【版權聲明】張轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3793601.htmlleetcode

相關文章
相關標籤/搜索