LeetCode刷題:27 Remove Element
問題描述:
Given an array nums and a value val, 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 1:
Given nums = [3,2,2,3], val = 3,
Your function should return length = 2, with the first two elements of nums being 2.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,1,2,2,3,0,4,2], val = 2,
Your function should return length = 5, with the first five elements of nums containing 0, 1, 3, 0, and 4.
Note that the order of those five elements can be arbitrary.
It doesn't matter what values are set beyond the returned length.
思路:
第一版沒有采用java中的封裝庫,直接寫邏輯。使用兩個指標,用來指示非val和val,示例如下:
nums=[0,1,2,2,3,0,4] val = 2 使用index作為非val指示,val_index作為val指示,
第一步:val_index=2, index=4 交換兩者位置 nums=[0, 1, 3, 2, 2, 0, 4]
第二步:val_index=3, index=5 交換兩者位置 nums=[0, 1, 3, 0, 2, 2, 4]
第三步 val_index=4, index=6 交換兩者位置 nums=[0, 1, 3, 0, 4, 2, 2]
當index移動到nums.length-1時說明已經全部交換完成,輸出非val資料多少,即val_index的值,程式碼如下
package leetcode_easy_27_RemoveElement;
class Solution {
public int removeElement(int[] nums, int val) {
if(nums.length==0)
return 0;
if(nums.length==1)
if(nums[0]==val)
return 0;
else
return 1;
int val_index = find_val_index(nums, 0, val);
if(val_index==-1)
return nums.length;
int nums_index = find_nums_index(nums, val_index, val);
if(nums_index==-1)
return find_val_index(nums, 0, val);
while(nums_index!=nums.length)
{
exchange_nums(nums, val_index, nums_index);
val_index = find_val_index(nums, val_index, val);
nums_index = find_nums_index(nums, nums_index, val);
if(nums_index==-1||val_index==-1)
break;
}
return val_index;
}
public void exchange_nums(int[] nums, int fir_idx,int sec_idx)
{
int tmp ;
tmp = nums[fir_idx];
nums[fir_idx] = nums[sec_idx];
nums[sec_idx] = tmp;
}
/*
* 找到初始位置
*/
public int find_val_index(int[] nums, int val_index, int val)
{
for(int i = val_index;i<nums.length;i++)
{
if(nums[i] == val)
{
return i;
}
}
return -1;
}
public int find_nums_index(int[] nums, int index, int val)
{
for(int i = index;i<nums.length;i++)
{
if(nums[i] != val)
return i;
}
return -1;
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {4,5};
System.out.println(solution.removeElement(nums, 5));
for(int i:nums){
System.out.print(i);
}
}
}
程式碼是通過了,但是效率非常之低。。於是選擇使用java的一些庫函式來提高效率
public int removeElement(int[] nums, int val) {
int i = 0;
int n = nums.length;
while (i < n) {
if (nums[i] == val) {
nums[i] = nums[n - 1];
// reduce array size by one
n--;
} else {
i++;
}
}
return n;
}
看了別人的solution之後發現,他們去除完element之後,數字出現的順序變了/