題目:

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.

 

思路:

移除陣列中含有指定的數值(val).

其中比較困難的部分是要在原本的陣列中移動元素.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#define MIN(a,b) (((a)<(b))?(a):(b))

int removeElement(int* nums, int numsSize, int val) {
    int i = 0,j;
    int count = 0;
    int idx = 0;
    int end = numsSize;
    for(i=0 ; i< end; i++){
    	if(nums[i]==val){
            for(j=i;j<(end-1);j++){
                nums[j]=nums[j+1];
            }  
            end--;
            i--;
        }else{
            count++;
        } 
    }
    
    return count;
}
文章標籤
全站熱搜
創作者介紹
創作者 Lung-Yu,Tsai 的頭像
Lung-Yu,Tsai

Lung-Yu,Tsai 的部落格

Lung-Yu,Tsai 發表在 痞客邦 留言(0) 人氣(78)