Find Positive Integer Solution for a Given Equation
给一个匿名递增方程, 问所有小于z的答案的可能. 因为是递增方程,所以用二叉搜索.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/* * // This is the custom function interface. * // You should not implement it, or speculate about its implementation * class CustomFunction { * // Returns f(x, y) for any given positive integers x and y. * // Note that f(x, y) is increasing with respect to both x and y. * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) * public int f(int x, int y); * }; */ class Solution { public List<List<Integer>> findSolution(CustomFunction customfunction, int z) { List<List<Integer>> res = new ArrayList<>(); int x = 1, y = z; while(x <= z && y > 0) { if(customfunction.f(x, y) == z) { res.add(Arrays.asList(x++, y--)); } else if(customfunction.f(x, y) > z) { y--; } else { x++; } } return res; } } |