twoSum Algorithm : How to improve this?

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

    Here is an Efficient Solution.

    Time Complexity - O(n) and Space Complexity - O(1)

    Sol: Will take two-pointer(start_pointer and end_pointer). Initially start_pointer point at the first index and end_pointer point to the last.

    Add both the element (sum = array[start_pointer] + array[last_pointer]. After that check, if the sum > target element or not. If yes decrease the end_pointer else increase start_pointer. If sum = target, means you got the indexes.

    public int[] twoSum(int[] numbers, int target) {
    
        int[] arr = new int[2]; // to store result
        int sum=0;
    
        int start_pointer=0;     
        int end_pointer = (numbers.length)-1;
    
        while(start_pointer<=end_pointer){
    
            sum=numbers[start_pointer]+numbers[end_pointer]; 
    
            if(sum>target)
                end_pointer-=1;
            else if(sum

提交回复
热议问题