[美团0813笔试] 第四题三元组

[美团0813笔试] 第四题三元组
求一个数组的三元组个数,
因为:a[i] - a[j] = 2*a[i] - a[k],
所以可以写成:a[i] + a[k] = 3*a[j]
那么可以定义一个递归函数searchInRange(int startIndex, int endIndex),每次在范围[i,k]内搜索满足上述公式的j,并逐渐缩小搜索范围
//
// Created by Harold on 2022/8/13/0013.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution{
private:
    int n_nums;
    int res = 0;
    vector<int> numList;
public:
    void getInput(){
        cin>>n_nums;
        vector<int> numInput(n_nums);
        for(int i = 0; i < n_nums; i++){
            cin>>numInput[i];
        }
        numList = numInput;
}
    void run(){
    getInput();
    getTheAns();
}

    void searchInRange(int startIndex, int endIndex){
        if(startIndex >= endIndex){
            return;
        }
        int sum_ik = numList[startIndex] + numList[endIndex];
        for(int i = startIndex+1; i < endIndex; i++){
            if(3 * numList[i] == sum_ik){
                res++;
            }
        }
        searchInRange(startIndex+1, endIndex);
        searchInRange(startIndex,endIndex-1);
    }
    void getTheAns(){
        searchInRange(0,numList.size()-1);
        cout<<res;
}
};
int main(){
    Solution s;
    s.run();
} 


#美团笔试##美团#
全部评论
你这个复杂度仍然是n^3的。searchInRange函数有2个参数,可以组成n^2种情况,内部复杂度O(n),总体n^3
点赞 回复 分享
发布于 2022-08-14 10:07

相关推荐

Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
5
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务