Two Sum(leetCode)

1470 단어
struct Node{
    int index;
    int value;
};
bool cmp(Node a,Node b)
{
    return a.value < b.value;
	
}


class Solution {
public:

    vector<int> twoSum(vector<int> &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
    Node node;
	int i,j;
	int size = numbers.size();
	vector<Node> nodes(size);
	vector<int> index;
	for(int i=0;i<size;i++)
	{
		node.index=i+1;
		node.value=numbers[i];
		nodes[i]=node;		
	}    
    sort(nodes.begin(),nodes.end(),cmp);
    for(i=0;i<size;i++)
    {
    	for(j=0;j<size;j++)
    	{
	    	if((nodes[i].value+nodes[j].value) == target)
	    	{
	    		if(nodes[i].index<nodes[j].index)
	    		{
					index.push_back(nodes[i].index);
					index.push_back(nodes[j].index);
					return index;
		    	}
		    	else if(nodes[i].index>nodes[j].index)
		    	{
					index.push_back(nodes[j].index);
					index.push_back(nodes[i].index);
					return index;
	    		}	    		
	    	}
	    	else if((nodes[i].value+nodes[j].value)>target	)
	        {
	        	continue; 		    		
	    	}
	    }
    }
    return index;
    }
};

좋은 웹페이지 즐겨찾기