forked from marsprince/SwordForOffer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLastRemaining.java
More file actions
43 lines (39 loc) · 848 Bytes
/
LastRemaining.java
File metadata and controls
43 lines (39 loc) · 848 Bytes
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
package Problem45;
import java.util.ArrayList;
public class LastRemaining {
/*
0,1...n-1这N个数字排成一个圆圈,从从数字0开始每次从这个圆圈里删除第M个数字.
求这个圈圈里剩下的最后一个数字
*/
public int lastRemaining (int count,int m) {
if(count < 1 || m < 1)
{
return -1;
}
ArrayList<Integer> cirList=new ArrayList<Integer>();
for (int i = 0; i < count; i++) {
cirList.add((int)i);
}
while(cirList.size()>1)
{
deleteCirlist(cirList, m);
}
return cirList.get(0);
}
private ArrayList<Integer> deleteCirlist(ArrayList<Integer> list,int m)
{
for (int i = 0; i < list.size(); i++) {
if(i==m-1)
{
list.remove(i);
return list;
}
if(i==list.size()-1)
{
i=-1;
m=m-list.size();
}
}
return list;
}
}