`

一个排好序的数组,找出两数之和为m的所有组合

 
阅读更多

 

public class Test {

    public static void main(String[] args) {

        //思路:既然是两个数字之后等于m,那么必然需要一个数小于或等于m/2,另一个数大于或等于m/2,而且数组的值要小于m
        int arr[] = new int[]{1, 2, 3, 5, 7, 7, 9, 10, 11, 12, 16, 17, 20};
        int m = 14;
        int count = 0;
        int forCount = 0;
        for (int i=0; i < arr.length-1; i++) {
            //小于m/2的值才参与计算
            if (arr[i] > m/2) {
                break;
            }
            for (int j = i+1; j < arr.length; j++) {
                //大于m/2的值才参与计算
                if (arr[j] < m/2) {
                    continue;
                }
                //值不能大于m
                if (arr[j] > m) {
                    break;
                }
                forCount++;
                if (arr[i] + arr[j] == m) {
                    count ++;
                    System.out.println("group " + count +": (" + arr[i] + ", " + arr[j] +")");
                }
            }
        }

        System.out.println("The number of loop times: " + forCount);

    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics