js css html算法

2475. 数组中不等三元组的数目

2023-06-12  本文已影响0人  红树_

LC每日一题,参考2475. 数组中不等三元组的数目,难度分1256。

题目

给你一个下标从 0 开始的正整数数组 nums 。请你找出并统计满足下述条件的三元组 (i, j, k) 的数目:

返回满足上述条件三元组的数目。

输入:nums = [4,4,2,4,3]
输出:3
解释:下面列出的三元组均满足题目条件:
- (0, 2, 4) 因为 4 != 2 != 3
- (1, 2, 4) 因为 4 != 2 != 3
- (2, 3, 4) 因为 2 != 4 != 3
共计 3 个三元组,返回 3 。
注意 (2, 0, 4) 不是有效的三元组,因为 2 > 0 。
输入:nums = [1,1,1,1,1]
输出:0
解释:不存在满足条件的三元组,所以返回 0 。

解题思路

枚举

class Solution {
    public int unequalTriplets(int[] nums) {
        int ans = 0;
        for(int i = 0; i < nums.length-2; i++) {
            int j = i + 1;
            while(j < nums.length-1) {
                if(nums[j] != nums[i]) {
                    int k = j + 1;
                    while(k < nums.length){
                        if(nums[k]!=nums[j]&&nums[k]!=nums[i]){
                            ans++;
                        }
                        k++;
                    }
                }
                j++;
            }
        }
        return ans;
    }
}

复杂度分析

排序

class Solution {
    public int unequalTriplets(int[] nums) {
        Arrays.sort(nums);
        int res = 0, n = nums.length, i = 0,j = 0;
        while (i < n) {
            while (j < n && nums[j] == nums[i]) {//枚举中间数个数(j-i)                                                                                    
                j++;
            }
            res += i * (j - i) * (n - j);
            i = j;
        }
        return res;
    }
}

复杂度分析

哈希表

class Solution {
    public int unequalTriplets(int[] nums) {
        int res = 0, n = nums.length;
        int[] hash = new int[1001];
        for(int i : nums) hash[i]++;
        int a = 0;
        for(int b : hash) {
            if(b > 0) {
                res += a * b * (n-a-b);
                a += b;
            }
        }
        return res;
    }
}

复杂度分析

上一篇 下一篇

猜你喜欢

热点阅读