yonatan.graber
BAN USER
Your solution won't show all options for [-1,-3,4,-1,1,-1,5]. @fword solution neither.
The following adjustment will do:
def get_sum(array):
cumsum_array = [0] + np.cumsum(array).tolist()
key_dict = {}
for index, cum_sum in enumerate(cumsum_array):
if cum_sum not in key_dict:
key_dict[cum_sum] = [index]
continue
for i,v in enumerate(key_dict[cum_sum]):
print array[v: index]
key_dict[cum_sum].append(index)
If the usage of Java's Pattern object is allowed, this is a simple Regular Expression question - each 'a*' turns into "(a)?" regex string, and each '.' turns into '.' regex string.
For example, "ab*..d" turns into "a(b)?..d" regex string. Compile the pattern and match away.
static boolean isMatch(String pat, String match) {
StringBuilder sb = new StringBuilder();
sb.append("^");
for (int i = 0; i < pat.length(); i++) {
if (i + 1 < pat.length() && pat.charAt(i + 1) == '*') {
sb.append('(').append(pat.charAt(i)).append(")?");
i++;
}
else {
sb.append(pat.charAt(i));
}
}
sb.append("$");
Pattern r = Pattern.compile(sb.toString());
return r.matcher(match).matches();
}
I believe that none of the suggestions above considered the case of decreasing AP (i.e. for the input {9,5,3,1} the result should be still 7). The following code does, in O(lgn) complexity:
int len = input.length;
int step = (input[0] + input[len - 1]) / (len + 1);
if (input[0] > input[len - 1])
step *= -1;
int low = 0;
int high = len - 1;
int lastGood = input[0];
while (low <= high) {
int p = (low + high) / 2;
int exp = input[0] + step * p;
if (exp == input[p]) {
lastGood = input[p];
low = p + 1;
}
else {
high = p - 1;
}
}
System.out.println(lastGood + step);
It fails for the input [1,0,4,-3,2] - return "7".
- yonatan.graber December 06, 2013