I got right answer in my vs2005 but wrong in oj in two-sum case 0,4,3,0?


  • 0
    K

    Input: [0,4,3,0], 0
    Output: 2, 3
    Expected: 1, 4
    why? in my vs2005,it's 1,4?!

    #include <stdafx.h>
    #include <iostream>
    #include <vector>
    #include <algorithm> 
    using namespace std;
    
    
    class Solution {
    public:
    vector<int> twoSum(vector<int> &numbers, int target) {
    	vector<int> tmpvi(numbers);
    	int tb=0,te=0;
    	sort(numbers.begin(),numbers.end());
    	
    	vector<int>::iterator begin = numbers.begin(),end = numbers.end()-1;
    	
    	while (begin<end)
    	{
    		if ((*begin)+(*end) == target)
    		{
    			tb = *begin;
    			te = *end;
    			break;
    		}else{
    			if ((*begin)+(*end)<target)
    				++begin;
    			else 
    				--end;
    		}
    	}
    	vector<int>::iterator i1 = find(tmpvi.begin(), tmpvi.end(), tb );
    	vector<int>::iterator i2 = find(tmpvi.begin(), tmpvi.end(), te );
    	
    	if (tb==te)
    	{
    		i2 = find(i2+1, tmpvi.end(), te );
    	}
    	
    	
    	int index1 = i1 - tmpvi.begin();
    	int index2 = i2 - tmpvi.begin();
    	if (index1>index2)
    	{
    		int tmp = index1;
    		index1 = index2;
    		index2 = tmp;
    	}
    
    	//printvec(tmpvi);
    	//printvec(numbers);
    
    	cout<<++index1<<", "<<++index2<<endl;
    	return numbers;
    }
    
    void printvec(vector<int> &numbers){
    	vector<int>::iterator begin = numbers.begin(),end = numbers.end();
    	while (begin!=end)
    	{
    		cout<<*begin++<<" ";
    	}
    	cout<<endl;
    }
    };
    
    
    int main(){
    int target = 0;
    int iarray[]={0,4,3,0};
    size_t count=sizeof(iarray)/sizeof(int);
    vector<int> ivec(iarray,iarray+count);
    
    Solution sl;
    sl.twoSum(ivec,target);
    
    return 0;
    

    }


  • 0
    K

    OK,i know. answer should be return instead of cout by myself


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.