1. Two Sum (Easy)

https://leetcode.com/problems/two-sum/

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

Hints

Solutions

  • Java
class Solution {
    HashMap<Integer, Integer> map = new HashMap<>();

    public int[] twoSum(int[] nums, int target) {
        int[] result = {0, 0};
        for (int i = 0; i < nums.length; i++) map.put(nums[i], i);

        Arrays.sort(nums);

        int i = 0, j = nums.length-1;
        while(i < j) {
            if (nums[i] + nums[j] < target) i++;
            if (nums[i] + nums[j] > target) j--;

            if (nums[i] + nums[j] == target) {
                result[0] = map.get(nums[i]);
                result[1] = map.get(nums[j]);
                if (map.get(nums[i]) > map.get(nums[j])) {
                    result[0] = map.get(nums[j]);
                    result[1] = map.get(nums[i]);
                }

                break;
            }
        }

        return result;
    }
}
Copyright © iovi.com 2017 all right reserved,powered by GitbookLast Modification: 2019-04-21 15:17:00

results matching ""

    No results matching ""