Chinaunix首页 | 论坛 | 博客
  • 博客访问: 42239
  • 博文数量: 9
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 94
  • 用 户 组: 普通用户
  • 注册时间: 2014-09-10 11:35
文章分类

全部博文(9)

文章存档

2015年(1)

2014年(8)

我的朋友

分类: C/C++

2014-09-28 00:19:02

题目描述:在一个整数数组中寻找符合A+B=C的组合,使C为最大
 输入、输出范例
输入:{ 1, 4, 2, 3 }
输出:1+3=4
输入:{ 2, 3, 1, 4, 5 }
输出:2+3=5
输入:{ 5, 8, 3, 1, 2, 4, 4 }
输出:4+4=8
思路:1:可以先对数组排序,快排的话时间复杂度为O(nlgn),把排好序的数组从最右端向左开始扫描,判断是否能找到符合条件的A与B,找到就停止扫描输出。否则继续扫描

代码如下:

点击(此处)折叠或打开

  1. #include "stdafx.h"
  2. #include "stdlib.h"
  3. #include "string.h"

  4. int cmp(const void *a,const void *b)
  5. {
  6.     if(*(int*)a>*(int*)b)
  7.         return 1;
  8.     else
  9.         return 0;

  10. }
  11. bool judgeSum(int &a,int &b,int *array,int j)
  12. {
  13.     int i=0;
  14.     int t=j-1;
  15.     while(i<t)
  16.     {
  17.         if(array[i]+array[t]>array[j])
  18.         {
  19.             t--;
  20.         
  21.         }
  22.         else if(array[i]+array[t]<array[j])
  23.         {
  24.             i++;
  25.         }else if(array[i]+array[t]==array[j])
  26.         {
  27.             a=array[i];
  28.             b=array[t];
  29.             return true;
  30.         
  31.         }
  32.     
  33.     
  34.     }
  35. return false;

  36. }
  37. int main(int argc, char* argv[])
  38. {
  39.     int array[6]={1,3,2,4,5,100};
  40.     qsort(array,6,sizeof(int),cmp);
  41.     for(int i=0;i<6;i++)
  42.     {
  43.         printf("%d\n",array[i]);
  44.     
  45.     }
  46.     int j=6;
  47.     int a,int b;
  48.     while(j)
  49.     {
  50.         if(judgeSum(a,b,array,j))
  51.         {
  52.             printf("%d+%d=%d",a,b,array[j]);
  53.             break;
  54.         
  55.         }
  56.         j--;
  57.     
  58.     
  59.     }


  60. }
以上代码整体复杂度为O(n2)。

阅读(1871) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~