LeetCode Remove Element
阿新 • • 發佈:2018-12-23
Problem
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.
跟從排好序的隊列出移除重複元素問題類似。從給定的佇列中移除給定的元素。最後,都需要把剩餘的有效元素放在佇列的開頭,可以理解為同一個問題。
Java 實現
package com.coderli.leetcode.algorithms.easy;
/**
* Given an array and a value, remove all instances of that value in place and return the new length.
* <p>
* Do not allocate extra space for another array, you must do this in place with constant memory.
* <p>
* The order of elements can be changed. It doesn't matter what you leave beyond the new length.
* <p>
* Example:
* Given input array nums = [3,2,2,3], val = 3
* <p>
* Your function should return length = 2, with the first two elements of nums being 2.
*
* @author li.hzh 2017-10-26
*/
public class RemoveElement {
public static void main(String[] args) {
RemoveElement removeElement = new RemoveElement();
System.out.println(removeElement.removeElement(new int[]{}, 3));
System.out.println(removeElement.removeElement(new int[]{2, 3, 3, 2}, 3));
System .out.println(removeElement.removeElementByAddCount(new int[]{2, 3, 3, 2, 4, 1}, 3));
}
public int removeElement(int[] nums, int val) {
int result = nums.length;
for (int i = nums.length - 1; i >= 0; i--) {
if (nums[i] == val) {
result--;
int temp = nums[result];
nums[result] = val;
nums[i] = temp;
}
}
return result;
}
public int removeElementByAddCount(int[] nums, int val) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
if (nums[i] != val) {
nums[result++] = nums[i];
}
}
return result;
}
}
分析
這裡給出兩個解法,removeElementByAddCount,是從前往後遍歷,跟remove duplicates from sorted array/ 問題解法思路一致了。
removeElement 解法,則是從後往前遍歷,遇到給定值的元素,交換一下位置即可。