C solution (binary search, 3ms)


  • 0
    T
    int* twoSum( int* numbers, int numbersSize, int target, int* returnSize )
    {
    	int	flag		= 0;
    	int	*results	= (int *) malloc( sizeof(int) * 2 );
    
    	for ( int i = 0; i < numbersSize - 1; i++ )
    	{
    		int l = i + 1, r = numbersSize - 1;
    		while ( l < r + 1 )
    		{
    			int temp = numbers[i] + numbers[(l + r) / 2];
    			if ( temp == target )
    			{
    				int j = (l + r) / 2;
    				if ( i < j )
    				{
    					results[0]	= i + 1;
    					results[1]	= j + 1;
    					printf( "index1=%d, index2=%d", results[0], results[1] );
    				} else {
    					results[1]	= i + 1;
    					results[0]	= j + 1;
    					printf( "index1=%d, index2=%d", results[1], results[0] );
    				}
    				flag = 1;
    				break;
    			} else if ( temp > target )
    			{
    				r = ( (l + r) / 2) - 1;
    			} else if ( temp < target )
    			{
    				l = ( (l + r) / 2) + 1;
    			}
    		}
    
    		if ( flag == 1 )
    		{
    			*returnSize = 2;
    			break;
    		}
    	}
    
    	if ( flag == 0 )
    	{
    		*returnSize = 0;
    	}
    
    	return(results);
    }
    

Log in to reply
 

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