[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/git-jhy/JavaArithmetic/master/src/LeetCode/LeetCode1.java [Back]  [Original]

package LeetCode;

import java.util.HashMap;

public class LeetCode1 {

    // 1. Two Sum
    // https://leetcode.com/problems/two-sum/description/
    // O(n)
    // O(n)

    public int[] twoSum(int[] nums, int target) {

        HashMap record = new HashMap();
        for(int i = 0 ; i < nums.length; i ++){
            int complement = target - nums[i];
            if(record.containsKey(complement)){
                int[] res = {i, record.get(complement)};
                return res;
            }
            record.put(nums[i], i);
        }

        throw new IllegalStateException("the input has no solution");
    }

    // , map
    // , record
    //  target = 2*a, numsa,
    // a, recorda :)
    public int[] twoSum2(int[] nums, int target) {

        HashMap record = new HashMap();
        for(int i = 0 ; i < nums.length ; i ++)
            record.put(nums[i], i);

        for(int i = 0 ; i < nums.length; i ++){
            if(record.containsKey(target - nums[i]))
                // ()...
                if(record.get(target - nums[i]) != i){
                int[] res = {i, record.get(target - nums[i])};
                return res;
            }

            record.put(nums[i], i);
        }

        throw new IllegalStateException("the input has no solution");
    }
}

Web Proxy Viewer  |  New URL  |  Original Page