Pay attention to overflow case


  • 0
    B

    In case of [1, 2147483646, 2147483647] , 2147483647

    public class Solution{
    	public int[] TwoSum(int[] numbers, int target) {
    		int low = 0;
    		int high = numbers.Length - 1;
    
    		while (low < high) {
    			int compare = this.CompareSum(numbers[low], numbers[high], target);
    			
    			if (compare == 0) return new[] { low + 1, high + 1 };
    			else if (compare < 0) ++low;
    			else --high; 	
    		}
    
    		return new [] { 0, 0 };
    	}
    
    	// assume a <= b
    	private int CompareSum(int a, int b, int target) {
    		int sum = a + b;
    
    		if (a > 0 && sum < 0) return 1;
    
    		if (b < 0 && sum >= 0) return -1;
    
    		if (sum == target) return 0;
    
    		return sum > target ? 1 : -1;
    	}
    }
    

Log in to reply
 

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