测试地址:https://leetcode.com/problems/remove-element/#/description
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.
Subscribe to see which companies asked this question.
package go.jacob.day619;
import java.util.Arrays;
public class Demo3 {
/*
* 运行时间:10ms
*/
public int removeElement(int[] A, int elem) {
int m = 0;
for(int i = 0; i < A.length; i++){
if(A[i] != elem){
A[m] = A[i];
m++;
}
}
return m;
}
/*
* Runtime: 12 ms
*/
public int removeElement_1(int[] nums, int val) {
if (nums == null || nums.length < 1)
return 0;
Arrays.sort(nums);
int length = nums.length;
int index = findVal(nums, val, 0, length - 1);
if (index != -1) {
length--;
int left = index - 1;
int right = index + 1;
while (left >= 0 && nums[left] == val) {
left--;
length--;
}
while (right < nums.length && nums[right] == val) {
right++;
length--;
}
for(int i=right;i<nums.length;i++){
nums[++left]=nums[i];
}
}
return length;
}
/*
* 二分查找
*/
private int findVal(int[] nums, int val, int begin, int end) {
if (begin > end)
return -1;
int mid = begin + (end - begin) / 2;
if (nums[mid] > val)
return findVal(nums, val, begin, mid - 1);
else if (nums[mid] < val)
return findVal(nums, val, mid + 1, end);
else
return mid;
}
}