首页 > 编程语言 > 详细

算法初步——哈希表A1048Find Coins

时间:2020-01-07 20:26:16      阅读:81      评论:0      收藏:0      [点我收藏+]

思路: two pointers

技术分享图片

 

#include <bits/stdc++.h>
#include<math.h>
#include <string>
using namespace std;
const int MAX_LEN = 100005;
bool cmp(int a,int b){
    return a>b;
}
int main(){
    //int temp[MAX_LEN];
    /*for(int i=0;i<MAX_LEN;++i){
        temp[i] = 0;
    }*/
    int n,m;
    cin>>n;
    cin>>m;
    int temp[n];
    for(int i=0;i<n;++i){
        cin>>temp[i];
    }
    sort(temp,temp+n,cmp);
    /*int count = 0;
    for(int i=0;i<MAX_LEN;++i){
        if(temp[i] > 0){
            count++;
        }
    }*/
    int fir = n-1;
    int end = 0;
    while(end != fir){
        if(temp[fir] + temp[end] < m){
            fir--;
        }
        if(temp[fir] + temp[end] > m){
            end++;
         }
         if(temp[fir] + temp[end] == m){
             cout<<temp[fir]<<" "<<temp[end];
             break;
         }   
    }
    if(end == fir){
        cout<<"No Solution";
    }
    system("pause");
    return 0;
} 

技术分享图片

 

 

注意要continue

#include <bits/stdc++.h>
#include<math.h>
#include <string>
using namespace std;
const int MAX_LEN = 100005;
bool cmp(int a,int b){
    return a>b;
}
int main(){
    //int temp[MAX_LEN];
    /*for(int i=0;i<MAX_LEN;++i){
        temp[i] = 0;
    }*/
    int n,m;
    cin>>n;
    cin>>m;
    int temp[n];
    for(int i=0;i<n;++i){
        cin>>temp[i];
    }
    sort(temp,temp+n,cmp);
    /*int count = 0;
    for(int i=0;i<MAX_LEN;++i){
        if(temp[i] > 0){
            count++;
        }
    }*/
    int fir = n-1;
    int end = 0;
    while(end != fir){
        if(temp[fir] + temp[end] < m){
            fir--;
            continue;//注意要continue 
        }
        if(temp[fir] + temp[end] > m){
            end++;
            continue;//注意要continue 
         }
         if(temp[fir] + temp[end] == m){
             cout<<temp[fir]<<" "<<temp[end];
             break;
         }   
    }
    if(end == fir){
        cout<<"No Solution";
    }
    system("pause");
    return 0;
} 

算法初步——哈希表A1048Find Coins

原文:https://www.cnblogs.com/JasonPeng1/p/12163089.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!