Why this happens?


  • 0
    J

    I can not show the screenshot , I'll just describe it.

    the test case is {3,2,4} 6
    my output is 2,3

    but it gives me the judgement "Wrong Answer".

    I wonder what's going on?

    public class Solution {
    public int[] twoSum(int[] nums, int target) {
        List<Integer> list = new ArrayList<Integer>();
        HashMap<Integer,Integer> hm = new HashMap<Integer,Integer>();
        int length = nums.length;
        for(int i=0;i<length;i++){
            list.add(nums[i]);
            hm.put(nums[i], i+1);
        }
        Collections.sort(list);
        int find=-1;
        for(int i=0;i<length;i++){
        	if((find = getItem(list,target-nums[i])) != -1 ){
        	    if(nums[i]!=list.get(find)){
                    System.out.println(hm.get(nums[i])+","+hm.get(list.get(find)));
                    break;
        	    }
        	}
        }
    	return nums;
    }
    
    private int getItem(List<Integer> list, int tar) {
    	int be = 0,en = list.size()-1;
    	int mid = -1;
    	while(be<=en){
    		mid = be + (en-be)/2;
    		if(tar == list.get(mid)) {
    			return mid;
    		} else {
    			if(tar > list.get(mid)){
    				be = mid + 1;
    			} else {
    				en = mid - 1;
    			}
    		}
    	}
    	if(be > en){
    		return -1;
    	}
    	if(tar == list.get(be)){
    		return be;
    	} else {
    		return -1;
    	}
    }
    

    }


  • 0
    Z
    public int[] twoSum(int[] numbers, int target) {
    	HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    	int[] result = new int[2];
    
    	for (int i = 0; i < numbers.length; i++) {
    		if (map.containsKey(numbers[i])) {
    			int index = map.get(numbers[i]);
    			result[0] = index + 1;
    			result[1] = i + 1;
    			break;
    		} else {
    			map.put(target - numbers[i], i);
    		}
    	}
    	return result;
    }
    

  • 0

    Look again, actually your output is [3,2,4].


  • 0
    J

    Yeah, that's the correct answer, thank you. But I need to know why my code failed. it's weird and I have to check by myself.


  • 0
    S

    there are many other testcases, you may check.


Log in to reply
 

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