设计一个算法,对于一个给定的包含n个整数的集合S和另一个给定的整数X,该算法可以在O(nlogn)时间内确定S中是否存在两个元素,使得它们的和恰为X。 C语言代码实现

#include <cstdio>
#include <cstdlib>
#include <cstring>
//快排 时间复杂度O(nlogn)
void quick_sort(int* arr, int l, int r) {
    if (l >= r) return;
    while (l < r) {
        int x = l, y = r;
        int z = arr[l];
        do {
            while (x <= y && arr[x] < z) x++;
            while (x <= y && arr[y] > z) y--;
            if (x <= y) {
                int temp = arr[x];
                arr[x] = arr[y];
                arr[y] = temp;
                x++, y--;
            }
        } while (x <= y);
        quick_sort(arr, l, y);
        l = x;
    }
}
//判断是否满足条件 O(n)时间复杂度
bool is_ok(int* A, int x, int len) {
	quick_sort(A, 0, len - 1);
	int i = 0, j = len - 1;
	while (i < j) {
		if (A[i] + A[j] == x) return true;
		else if (A[i] + A[j] > x) j--;
		else i++;
	}
	return false;
}

int main() {
	int A[8] = {3, 41, 52, 26, 38, 57, 9, 49};
	int x;
	while (scanf("%d", &x) != EOF) {
		printf("%d\n", is_ok(A, x, 8));
	}

	return 0;
}

理论证明

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值