Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Two Sum

import java.util.HashMap;
import java.util.Map;

public class HelloWorld{

    public static void main(String []args){
        int[] nums = {4,2,6,10,5,3};
        
        int target = 2;
        int[] result = twoSum(nums, target);
        System.out.println(result[0] + " + " + result[1] + " = " + target);
    }
    
    static int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map = new HashMap();
        
        for(int i = 0; i < nums.length; i++) {
            int compliment = target - nums[i];
            // System.out.println("num "+ nums[i] + ", " + compliment);
            Integer found = map.get(compliment);
            // System.out.println("   found "+ found);
            // if(found != null) {
            //                 System.out.println("   value "+ map.get(compliment));
            // }
            if(map.get(compliment) != null) {
                return new int[]{nums[map.get(compliment)], nums[i]};
            }
            map.put(nums[i], i);
            // printKeys(map);
            
        }
        throw new Error("No sum found.");
    }
    
    static void printKeys(Map<Integer, Integer> map) {
        for(Integer key : map.keySet()) {
            System.out.println("  key " + key);
        }
    }
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.