twoSum Algorithm : How to improve this?

前端 未结 22 2095
礼貌的吻别
礼貌的吻别 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:55

    We can do with HashMap and the time complexity would be O(n)

    public class ReturnIndicesOfElementsAddToSum {
    
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 18;
    
        if(!getIndices(nums,target)) {
            System.out.println("No such numbers found");
        }
    
    }
    
    static boolean getIndices(int[] nums, int target) {
        Map indexMap = new HashMap<>();
        boolean numFound = false;
        for(int i=0;i

    }

提交回复
热议问题