titan2400

Two Sum (Sorted Input) - LeetCode

Oct 29th, 2025 (edited)
998
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.63 KB | Source Code | 0 0
  1. // Two Sum - Input Array is sorted - https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
  2.  
  3. class Solution {
  4.     // Two pointers
  5.     // Time Complexity: O(n)
  6.     // Space Complexity: O(1)
  7.     public int[] twoSum(int[] numbers, int target) {
  8.         int i = 0, j = numbers.length - 1;
  9.  
  10.         while(i < j) {
  11.             if(numbers[i] + numbers[j] == target) {
  12.                 return new int[]{i+1, j+1};
  13.             }
  14.             else if (numbers[i] + numbers[j] > target) {
  15.                 j--;
  16.             } else {
  17.                 i++;
  18.             }
  19.         }
  20.  
  21.         return new int[]{};
  22.        
  23.     }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment