twoSum Algorithm : How to improve this?

前端 未结 22 2057
礼貌的吻别
礼貌的吻别 2021-02-06 01:38

I felt like doing an algorithm and found this problem on leetcode

Given an array of integers, find two numbers such that they add up to a specific target num

22条回答
  •  囚心锁ツ
    2021-02-06 01:54

    Here is the answer using HashMap in java with two passes of the array. Assuming that there are no duplicate elements in the array and there is exactly one solution exists.

    import java.util.HashMap;
    
    public class TwoSum {
    
        int[] index = new int[2];
        public int[] twoSum(int[] nums, int target)
        {
            int length = nums.length;
            //initialize return values assuming that pair for the given target
            //doesn't exist
            index[0]=-1;
            index[1]=-1;
            //sanity check
            if(length<1) return index;
    
            HashMap numHash = new HashMap<>(length);
            //get the values from array into HashMap assuming that there aren't duplicate values
            for(int i=0; i

提交回复
热议问题