Why it reports that java.lang.ArrayIndexOutOfBoundsException in line 19 with the exmaple of [3,2,4] 6 ?


  • 0
    D

    here is my code as follows:

    line1 public class Solution {

    public int[] twoSum(int[] numbers, int target) {
    
        int mod = target + 1;
    	int hashmap[] = new int[mod];
    	int a[] = {0,0};
    	
    	for(int i=0;i< numbers.length;i++)
    	{
    		if(numbers[i] > target)
    			continue;
    		hashmap[numbers[i]] = i+1; 
    	}
        
    	for(int i=0;i<numbers.length;i++)
    	{
    		if( numbers[i]<mod)
    		{
    
    			int temp = target - numbers[i];
    

    line19 if(hashmap[temp] != 0){

    			    if(target%2 == 0 && numbers[i] == target/2)
            	        continue;
        			if(i+1 < hashmap[(target - numbers[i])] ){
    
        				a[0] = i+1;
            			a[1] = hashmap[(target - numbers[i])];
        			}else
        			{
    
        				a[0] = hashmap[(target - numbers[i])];
            			a[1] = i+1;
        			}
        			return a;
    			}
        			
    		}
    	}
    		
    	return a;
    } 
    

    }


  • 0
    Y

    I don't think the example [3,2,4] 6 can lead to java.lang.ArrayIndexOutOfBoundsException in line 19
    But obviously it is sure that the code 'hashmap[numbers[i]] = i+1;' will lead to java.lang.ArrayIndexOutOfBoundsException if numbers[i] < 0.


  • 0
    D

    yes, I quitely agree with you, and the problem you've mentioned is the key. I didn't consider the condition that numbers[i] < 0. Thank you !


Log in to reply
 

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