Accepted Java - O(n lg(n)) solution-7ms-beats 91.7%


  • 0
    M
    	private static int[] twoSum(final int[] nums, final int target) {
    		int[] indexes = new int[2];
    		int index1;
    		int index2;
    		int copynums[] = Arrays.copyOf(nums, nums.length);
    		Arrays.sort(copynums);
    		for (int i = 0; i < copynums.length - 1; i++) {
    			index1 = i;
    			int index = Arrays.binarySearch(copynums, i + 1, copynums.length, target - copynums[index1]);
    			if (index > 0) {
    				index2 = index;
    				indexes[0] = -1;
    				indexes[1] = -1;
    				for (int j = 0; (j < nums.length && (indexes[0] < 0 || indexes[1] < 0)); j++) {
    					if (nums[j] == copynums[index1] || nums[j] == copynums[index2]) {
    						if (indexes[0] < 0) {
    							indexes[0] = j;
    						} else {
    							indexes[1] = j;
    						}
    					}
    				}
    				System.out.println(Arrays.toString(indexes));
    				return indexes;
    			}
    		}
    		System.out.println(Arrays.toString(indexes));
    		return indexes;
    	}
    

Log in to reply
 

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