| 网站首页 | 业界新闻 | 群组 | 人才 | 下载频道 | 博客 | 代码贴 | 编程论坛
共有 291 人关注过本帖
标题:关于向量的问题,新手求教
只看楼主 收藏
moox
Rank: 2
来 自:福建
等 级:论坛游民
帖 子:91
专家分:93
注 册:2017-1-21
  得分:0 
回复 5楼 rjsp
vector<vector<int> >是指二维数组对吧,我不明白为什么要用到二维数组...
我把二维数组换成一维的就不会提示有错了.但还是出不了结果...
程序代码:
#include<iostream>
#include<vector>
using namespace std;
vector<int> threeSum(vector<int> &num)
{
    vector<int> result;
    int len=num.size();
    for(int i=0;i<len;++i)
    {
        int target=0-num[i];
        int start=i+1,end=len-1;
        while(start<end)
        {
            if(num[start]+num[end]==target)
            {
                result.push_back(num[i]);
                result.push_back(num[start]);
                result.push_back(num[end]);
                start++;end--;
                while(start<end&&num[start]==num[start-1])
                {
                    start++;
                }
                while((start<end) && (num[end]==num[end+1]))
                {
                    end--;
                }
            }
            else if(num[start]+num[end]<target) start++;
            else end--;
        }
        while(i<len) if(num[i]==num[i+1]) i++;
    }
    for(vector<int>::iterator it=result.begin ();it!=result.end ();it++)
        cout<<it<<' ';
    cout<<endl;
    return result;
}

void main(){
    int a[8]={-9,-3,-1,0,1,2,3,4};
    vector<int> num(a,a+8);
    vector<int> b(threeSum(num));
    for(vector<int>::iterator it=b.begin();it!=b.end();++it)
        cout<<*it<<" ";
    cout<<endl;
}
2017-12-28 17:09
moox
Rank: 2
来 自:福建
等 级:论坛游民
帖 子:91
专家分:93
注 册:2017-1-21
  得分:0 
谢谢各位大佬,问题解决了,虽然程序很丑,但学到了,不少东西.
程序代码:
#include<iostream>
#include<vector>
using namespace std;
vector<int> threeSum(vector<int> &num)
{
    vector<int> result;
    int len=num.size();
    for(int i=0;i<len;++i)
    {
        int target=0-num[i];
        int start=i+1,end=len-1;
        while(start<end)
        {
            if(num[start]+num[end]==target)
            {
                result.push_back(num[i]);
                result.push_back(num[start]);
                result.push_back(num[end]);
                start++;end--;
                while(start<end&&num[start]==num[start-1])
                {
                    start++;
                }
                while((start<end) && (num[end]==num[end+1]))
                {
                    end--;
                }
            }
            else if(num[start]+num[end]<target) start++;
            else end--;
        }
        if(num[i]==num[i+1]) while(i<len&&num[i]==num[i+1]) i++;
    }
    return result;
}

void main(){
    int a[8]={-9,-3,-1,0,1,2,3,4};
    vector<int> num(a,a+8);
    vector<int> b(threeSum(num));
    for(vector<int>::iterator it=b.begin();it!=b.end();++it)
        cout<<*it<<" ";
    cout<<endl;
}

2017-12-28 18:26







关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.112208 second(s), 9 queries.
Copyright©2004-2018, BCCN.NET, All Rights Reserved