题目描述:在有序数组中找出两个数,使它们的和为 target。

    解题思路,使用双指针的方式,根据比较结果移动指针,得到想要的结果

    1. package com.chason.suanfa;
    2. /**
    3. * <p>description: </p>
    4. * <p>Date: 2021/8/27</p>
    5. * <p>modify:</p>
    6. *
    7. * @author zhang zhangs@deepblueai.com
    8. **/
    9. public class FindToItemAdd2Target {
    10. public static void main(String[] args) {
    11. int[] arr ={1,3,4,6,8,9,12,45,67};
    12. int[] res = toSum(arr,20);
    13. System.out.println(res[0]);
    14. System.out.println(res[1]);
    15. }
    16. public static int[] toSum(int[] arr, int target) {
    17. int head = 0, tail = arr.length - 1;
    18. while (head < tail) {
    19. int sum = arr[head] + arr[tail];
    20. if (target == sum) {
    21. return new int[]{head+1,tail+1};
    22. }
    23. if (arr[head] + arr[tail] > target) {
    24. tail--;
    25. } else {
    26. head++;
    27. }
    28. }
    29. return null;
    30. }
    31. }