leetcode-182周赛-5368. 找出数组中的幸运数

题目描述:

leetcode-182周赛-5368. 找出数组中的幸运数

 

 python提交:O(N^3)

class Solution:
    def numTeams(self, rating: List[int]) -> int:
        ans = 0
        for i in range(len(rating)):
            for j in range(i,len(rating)):
                for k in range(j,len(rating)):
                    if rating[i] < rating[j] < rating[k] or rating[i] > rating[j] > rating[k]:
                        ans += 1
        return ans

java提交:O(N^3)

class Solution {
    public int numTeams(int[] rating) {
        int ans = 0;
        for(int i=0;i<rating.length;i++){
            for(int j=i+1;j<rating.length;j++){
                for(int k=j+1;k<rating.length;k++){
                    if(rating[i]<rating[j] &&rating[j]<rating[k]||rating[i]>rating[j] &&rating[j]>rating[k])
                        ans += 1;
          
                }
            }

        }
        return ans;

    }
}

优化:

class Solution:
    def numTeams(self, rating: List[int]) -> int:
        def calc(S):
            n=len(S)
            re=0
            for i in range(n):
                l=0
                r=0
                for j in range(0,i):
                    if S[j]<S[i]:
                        l+=1
                for j in range(i+1,n):
                    if S[j]>S[i]:
                        r+=1
                re+=l*r
            return re
        ans=calc(rating)
        rating.reverse()
        ans+=calc(rating)
        return ans

 

上一篇:洛谷:P1002 过河卒


下一篇:Rocky Linux镜像在阿里云镜像站首发上线