can someone help me to point out the problem in my code?


  • 0
    D

    I try to wirte a method to use binary search to solve this problem by fix and loop the first element and then binary search the second one in the other part, but it's weird that my code seems to get into a dead loop, and I've read multiple times but failed to figure out the fault, can someone help me? thanks in advance, here is the code

    public static int[] twoSum(int[] numbers, int target){
    		int n = numbers.length;
    		int[] result=new int[2];
    		for(int i=0;i<n;i++){
    			int index1 = i+1;
    			int sub=target-numbers[i];
    			int lo=index1;
    			int hi=n-1;
    			int index2=index1+1;
    			
    			while(lo<=hi){
    				int mid=(lo+hi)>>>2;
    				if(numbers[mid]==sub){
    					index2=mid+1;
    					break;
    				}
    				else if(numbers[mid]<sub){
    					lo=mid+1;
    				}
    				else{
    					hi=mid-1;
    				}
    			}
    			if(lo<=hi){
    				 result=new int[]{index1,index2};
    				 break;
    			}
    		}
    		return result;		
    	}
    

Log in to reply
 

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