-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoveElement.java
More file actions
65 lines (62 loc) · 1.59 KB
/
RemoveElement.java
File metadata and controls
65 lines (62 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.wg.leetcode;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
/*
* 27:移除元素
* 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.
*/
public class RemoveElement {
/**
* 第一种方法:和moveZeros方法一样:逐个遍历比较,不相等则index加1,然后返回index,时间复杂度O(n)
* @param nums
* @param val
* @return
*/
public static int removeElement(int[]nums,int val){
if(nums==null||nums.length==0) return 0;
int index=0;
for(int num:nums){
if(num!=val) nums[index++]=num;
}
return index;
}
/**
* 利用两个指针
* @param nums
* @param val
* @return
*/
public static int removeElement1(int[]nums,int val){
int index1=0;
int index2=nums.length-1;
//两种方式都可以
/* while(index1<=index2){
if(nums[index1]!=val) index1++;
else if(nums[index2]==val) index2--;
else{
//交换
int temp=nums[index1];
nums[index1++]=nums[index2];
nums[index2--]=temp;
}
}*/
while(index1<=index2){
while(index1<index2 && nums[index1]!=val)index1++;
while(index1<index2 && nums[index2]==val)index2--;
//交换
int temp=nums[index1];
nums[index1++]=nums[index2];
nums[index2--]=temp;
}
return index1;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] nums={3,2,4,2,3};
System.out.println(removeElement(nums, 3));
}
}