Grokking-the-Coding-Interview-Patterns-for-Coding-Questions icon indicating copy to clipboard operation
Grokking-the-Coding-Interview-Patterns-for-Coding-Questions copied to clipboard

Fixed of Two Sum problem

Open tanzirbd opened this issue 1 year ago • 0 comments

class Solution { public int[] twoSum(int[] nums, int target) { int[] copyArray = Arrays.copyOf(nums, nums.length); Arrays.sort(copyArray); int i=0, j=copyArray.length-1; int[] arr= new int[2]; int num1=0, num2=0; while(i<j){ int sum= copyArray[i] + copyArray[j]; if(sum < target ) i++; else if(sum > target) j--; else { num1=copyArray[i]; num2=copyArray[j]; break; } } for(int k=0;k<nums.length;k++){ if(num1==nums[k] && arr[0]==0) arr[0]=k; else if(num2==nums[k]) arr[1]=k; } return arr; } }

tanzirbd avatar Mar 16 '24 16:03 tanzirbd