twoSum Algorithm : How to improve this?

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

    My solution to this problem would be,

    public int[] twoSums(int[] unsortedNum, int target) {
            int[] nums = Arrays.copyOf(unsortedNum, unsortedNum.length);
            Arrays.sort(nums);
            boolean isResultFound = false;
            int start = 0;
            int end = nums.length-1;
            while(!(start > end)) {
                if(nums[start]+nums[end] > target){
                    end--;
                } else if (nums[start]+nums[end] < target){
                    start++;
                } else if(nums[start] + nums[end] == target){
                    isResultFound = true;
                    break;
                }
            }
            if(isResultFound){
                int s = -1;
                int e = -1;
                for(int i = 0; i< unsortedNum.length; i++){
                    if(s != -1 && e != -1){
                        break;
                    }
                    if(s == -1 && unsortedNum[i] == nums[start]){
                        s = i;
                    } else if(e == -1 && unsortedNum[i] == nums[end]) {
                        e = i;
                    }
                }
                return new int[] {s,e};
            }
            // for element not found
            return new int[]{-1,-1};
        }
    

    In the end, if you get -1, -1 as the index then you can say that elements not found which could sum to the target element.

提交回复
热议问题