中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下k sum,欢迎指教
- public class KSumSmaller {
- public static void main(String[] args) {
- int[] arr = {3, 1, 5, 2, 4};
- int res = findKSumSmaller(arr, 9, 3);
- System.out.println(res);
- }
-
- static int count = 0;
- public static int findKSumSmaller(int[] arr, int target, int k) {
- if (arr == null || arr.length == 0) {
- return 0;
- }
- Arrays.sort(arr);
- if (k == 1) {
- for (int i : arr) {
- if (i < target) {
- count += 1;
- }
- }
- } else if (k == 2) {
- findTwoSumSmaller(arr, target, 0);
- } else {
- helper(arr, target, 0, k);
- }
- return count;
- }
-
- public static void findTwoSumSmaller(int[] arr, int target, int start) {
- if (arr == null || arr.length == 0) {
- return;
- }
- Arrays.sort(arr);
- int left = start;
- int right = arr.length - 1;
- while (left < right) {
- int sum = arr[left] + arr[right];
- if (sum < target) {
- count += right - left;
- left++;
- } else {
- right--;
- }
- }
- }
- private static void helper(int[] arr, int target, int start, int k) {
- if (start >= arr.length) {
- return;
- }
- if (k == 2) {
- findTwoSumSmaller(arr, target, start);
- } else {
- if (arr[start] < target) {
- helper(arr, target - arr[start], start + 1, k - 1);
- helper(arr, target, start + 1, k);
- }
- }
- }
- }
复制代码 |
|