美文网首页数据结构和算法分析数据结构与算法
Leetcode-167 两数之和 II - 输入有序数组

Leetcode-167 两数之和 II - 输入有序数组

作者: itbird01 | 来源:发表于2021-09-25 14:07 被阅读0次

167. 两数之和 II - 输入有序数组

解题思路

1.第一种解法,暴力解法,嵌套for循环--可能超时
2.第二种解法
1)题意分析,为有序数组,并且是非递减
2)两个指针,left从前往后,right从后往前,找寻数字
3)如果相加结果,大于target,则right--
4)如果相加结果,小于target,则left++
5)如果相加等于target,则输出结果
6)如果left>=right,则无结果

解题遇到的问题

1.用双指针的思想去解题

##解法1(可能超时)
class Solution {
    public static int[] twoSum(int[] numbers, int target) {
        for (int i = 0; i < numbers.length; i++) {
            int j = i + 1;
            while (j < numbers.length) {
                if (numbers[i] + numbers[j] == target) {
                    return new int[]{i + 1, j + 1};
                }
                j++;
            }
        }
        return new int[]{1, 1};
    }
}

##解法2
class Solution {
  public static int[] twoSum(int[] numbers, int target) {
        int left = 0, right = numbers.length - 1;
        while (left < right) {
            if (numbers[left] + numbers[right] == target) {
                return new int[]{left + 1, right + 1};
            } else if (numbers[left] + numbers[right] > target) {
                right--;
            } else {
                left++;
            }
        }
        return new int[]{1, 1};
    }
}

相关文章

网友评论

    本文标题:Leetcode-167 两数之和 II - 输入有序数组

    本文链接:https://www.haomeiwen.com/subject/rwbegltx.html