• 给定差值的组合 A


     

     思路:排序+二分

    代码:

    #include <iostream>
    #include <vector>
    #include <algorithm>
    using namespace std;
    
    bool BinSerch(const vector<int>& arr, int start, int target)
    {
        int left = start;
        int right = arr.size() - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                return true;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else if (arr[mid] > target) {
                right = mid - 1;
            }
        }
        return false;
    }
    // 待实现函数,在此函数中填入答题代码
    int Proc(const vector<int>& arr, int diff)
    {
        // 在此添加你的代码
        size_t arrLen = arr.size();
        vector<int> arrCur;
        arrCur.assign(arr.begin(), arr.end());
        int cnt = 0;
        sort(arrCur.begin(), arrCur.end());
        for (size_t i = 0; i < arrLen - 1; i++) {
            if ((diff > 0 && BinSerch(arrCur, i + 1, arrCur[i] + diff)) ||
            (diff < 0 && BinSerch(arrCur, i + 1, arrCur[i] - diff))) {
                cnt++;
            }
        }
        return cnt;
    }
    
    // 以下为考题输入输出框架,此部分代码不建议改动
    int main()
    {
        string line;
        getline(cin, line);
        int diff = stoi(line);
    
        getline(cin, line);
        int n = stoi(line);
        vector<int> arr(n);
        for (int i = 0; i < n; ++i) {
            cin >> arr[i];
        }
        cout << Proc(arr, diff) << endl;
        return 0;
    }
  • 相关阅读:
    BeautifulSoup的基本用法
    [leedcode 189] Rotate Array
    [leedcode 187] Repeated DNA Sequences
    [leedcode 179] Largest Number
    [leedcode 174] Dungeon Game
    [leedcode 173] Binary Search Tree Iterator
    [leedcode 172] Factorial Trailing Zeroes
    [leedcode 171] Excel Sheet Column Number
    [leedcode 169] Majority Element
    [leedcode 168] Excel Sheet Column Title
  • 原文地址:https://www.cnblogs.com/gcter/p/15911404.html
Copyright © 2020-2023  润新知