2012-09-12 10:39:41Morris
[TopCoder][SRM553] Suminator
一樣, 看了題解之後有點慚愧, 寫得不是很好看,
這題要特別注意回傳一定要整數, 且如果代入的數字是 0, 要把它當功能來看待
public class Suminator {
public int findMissing(int[] ar, int want) {
long[] stack = new long[1000];
long[] p = new long[1000];
int idx = 0;
// x = 0
for(int i = 0; i < ar.length; i++) {
if(ar[i] == 0 || ar[i] == -1) {
if(idx >= 2) {
stack[idx-2] = stack[idx-2] + stack[idx-1];
idx --;
}
} else {
stack[idx] = ar[i];
idx++;
}
}
if(idx-1 >= 0 && stack[idx-1] == want)
return 0;
System.out.println("2");
idx = 0;
for(int i = 0; i < ar.length; i++) {
if(ar[i] == 0) {
if(idx >= 2) {
stack[idx-2] = stack[idx-2] + stack[idx-1];
p[idx-2] = p[idx-2] + p[idx-1];
idx --;
}
} else if(ar[i] == -1) {
p[idx] = 1;
stack[idx] = 0;
idx++;
} else {
p[idx] = 0;
stack[idx] = ar[i];
idx++;
}
}
if(idx-1 < 0) return -1;
if(p[idx-1] == 0) return -1;
if((want - stack[idx-1])%p[idx-1] == 0) {
if(want - stack[idx-1] >= 0 && ((want - stack[idx-1])/p[idx-1]) != 0)
return (int)((want - stack[idx-1])/p[idx-1]);
else
return -1;
}
return -1;
}
}
這題要特別注意回傳一定要整數, 且如果代入的數字是 0, 要把它當功能來看待
public class Suminator {
public int findMissing(int[] ar, int want) {
long[] stack = new long[1000];
long[] p = new long[1000];
int idx = 0;
// x = 0
for(int i = 0; i < ar.length; i++) {
if(ar[i] == 0 || ar[i] == -1) {
if(idx >= 2) {
stack[idx-2] = stack[idx-2] + stack[idx-1];
idx --;
}
} else {
stack[idx] = ar[i];
idx++;
}
}
if(idx-1 >= 0 && stack[idx-1] == want)
return 0;
System.out.println("2");
idx = 0;
for(int i = 0; i < ar.length; i++) {
if(ar[i] == 0) {
if(idx >= 2) {
stack[idx-2] = stack[idx-2] + stack[idx-1];
p[idx-2] = p[idx-2] + p[idx-1];
idx --;
}
} else if(ar[i] == -1) {
p[idx] = 1;
stack[idx] = 0;
idx++;
} else {
p[idx] = 0;
stack[idx] = ar[i];
idx++;
}
}
if(idx-1 < 0) return -1;
if(p[idx-1] == 0) return -1;
if((want - stack[idx-1])%p[idx-1] == 0) {
if(want - stack[idx-1] >= 0 && ((want - stack[idx-1])/p[idx-1]) != 0)
return (int)((want - stack[idx-1])/p[idx-1]);
else
return -1;
}
return -1;
}
}