好友请求

http://www.lintcode.com/zh-cn/problem/friend-request/

public class Solution {
    /**
     * @param ages: The ages
     * @return: The answer
     */
    public int friendRequest(int[] ages) {
        // Write your code here
        int[] counts = new int[151];
        for (int i = 0; i < ages.length; i++) {
            int age = ages[i];
            counts[age]++;
        }
        int res = 0;
        for (int i = 1; i < counts.length; i++) {
            int count = counts[i];
            if (count > 0) {
//                找到年龄为i的人可以发送的次数;
                int nums = 0;
                for (int j = 1; j < counts.length; j++) {
                    if (j <= i / 2 + 7 || j > i || (j < 100 && i > 100)) {
                        continue;
                    }
                    int count1 = counts[j];
                    if (count1 > 0) {
                        if (i == j) {
//                            同龄的时候要减去自己
                            count1--;
                        }
                        nums += count1;
                    }
                }
                res += nums * count;
            }
        }
        return res;
    }

}

你可能感兴趣的:(好友请求)