Two sum in sorted array
Java
Medium
3 views
Problem Description
Task: array is sorted. Return indices of two numbers that sum to target, else [-1,-1]. Use two pointers.
Output Format
Return value
Constraints
Return 0-based indices.
Official Solution
static int[] twoSumSorted(int[] a,int target){int l=0,r=a.length-1;while(l<r){int s=a[l]+a[r];if(s==target) return new int[]{l,r};if(s<target) l++;else r--;}return new int[]{-1,-1};}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!