Created
July 17, 2016 06:14
-
-
Save jianminchen/decb1042a4e8e66c50be2c80c70f063a to your computer and use it in GitHub Desktop.
DiffK - facebook code lab - Your solution is not well optimized for runtime.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int diffPossible(List<Integer> a, int b) { | |
if(a == null || a.size() == 0) | |
return 0; | |
int sum = a.get(0).intValue() + b; | |
int pos = getPos(a, sum); | |
if(pos < a.size() && a.get(pos) == sum) | |
return 1; | |
for(int i=1; i< a.size() && pos < a.size(); i++) | |
{ | |
int tmpSum = a.get(i).intValue() + b; | |
for(int j= pos; j< a.size(); j++) | |
{ | |
int tmp2 = a.get(j).intValue(); | |
if(tmp2 == tmpSum) | |
return 1; | |
else if(tmp2 < tmpSum) | |
continue; | |
else{ | |
pos = j; | |
break; | |
} | |
} | |
} | |
return 0; | |
} | |
public int getPos(List<Integer> a, int sum) | |
{ | |
int len = a.size(); | |
int start = 0; | |
int end = len -1; | |
if(sum > a.get(end).intValue() || sum < a.get(start).intValue()) | |
return len; | |
while(start < end) | |
{ | |
int mid = (start + end)/ 2; | |
int tmp = a.get(mid).intValue(); | |
if(tmp == sum) | |
return mid; | |
else if(tmp < sum) | |
start = mid; | |
else | |
end = mid; | |
} | |
return start; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment