Skip to content

Instantly share code, notes, and snippets.

@shz117
Created October 17, 2013 04:30
Show Gist options
  • Save shz117/7019224 to your computer and use it in GitHub Desktop.
Save shz117/7019224 to your computer and use it in GitHub Desktop.
Time O(n) Space O(n) Comments and advices are welcome! Thanks!
public long[] products(long[] a){
if (a==null || a.length == 0 || a.length == 1) return a;
long[] ret = new long[a.length];
long product = 1;
int zeros = 0;
int zeropos = 0;
for (int i = 0; i<a.length;i++){
if (a[i] == 0){
zeros++;
zeropos = i;
} else
product*=a[i];
}
if (zeros > 1) return ret;
if (zeros == 1){
ret[zeropos] = product;
return ret;
}
for (int i = 0; i<a.length;i++){
ret[i] = product/a[i];
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment