紧接着上一篇数组博文的下一篇;上一篇有一个数三退一的游戏,在这里还有一个很能体现面向对象的解法,还运用了稍显高大上的双向环哦~
public class Count3Quit {
public static void main(String[] args) {
KidCircle kd = new KidCircle(500);
int countNum = 0;
Kid k = kc.first;
while(kc.count > 1) {
countNum++;
if(countNUm == 3) {
countNum = 0;
kc.delete(k);
}
k = k.right;
}
System.out.println(kc.first.id);
}
}
class Kid {
int id;
Kid left;
Kid right;
}
class KidCircle {
int count = 0;
Kid first,last;
KidCircle(int n) {
for(int i = 0; i < n; i++) {
add();
}
}
void add() {
Kid k = new Kid();
k.id = count;
if(count <= 0) {
first = k;
last = k;
k.left = k;
k.right = k;
} else {
last.right = k;
k.left = last;
k.right = first;
first.left = k;
last = k;
}
count++;
}
void delete(Kid k) {
if(count <= 0) {
return;
} else if(count == 1) {
first = last = null;
} else {
k.left.right = k.right;
k.right.left = k.left;
if(k == first) {
first = k.right;
} else if(k == last) {
last = k.left;
}
}
}
}
接下来上一位数组里面一个不得不提的经典小程序,即二分法查找
public class TestSearch {
public static void main(String[] args) {
int a[] = {1,3,6,8,9,10,12,18,20,34};
int i = 12;
System.out.println(binarySearch(a,i));
}
public static int binarySearch(int[] a, int num) {
if(a.length == 0) {
return -1;
}
int startPos = 0;
int endPos = a.length - 1;
int m = (startPos + endPos) / 2;
while(startPos <= endPos) {
if(a[m] == num) {
return m;
}
if(a[m] > num) {
endPos = m - 1;
}
if(a[m] < num) {
startPos = m + 1;
}
m = (startPos + endPos) / 2;
}
}
}
“`