Java simple solution using two pointers

  • 0

    This algorithm reminds a little bit of QuickSort, where I use two pointers marking the starting and ending indexes. So, if the sum is greater than the target I decrement the end, if it is less than the target I increment the start. If I found the correct sum I return the indexes + 1.

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int start = 0;
            int end = numbers.length - 1;
            while (start <= end) {
                if ((numbers[start] + numbers[end]) > target) {
                } else if ((numbers[start] + numbers[end]) < target) {
                } else {
            return new int[]{start+1, end+1};

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.