对撞指针

对撞指针.png
  • 程序:
package com.cqu.test1;

public class Solution2 {
    public static int[] twoSum(int[] nums,int target) {
        if(nums==null||nums.length==0) {
            return null;
        }
        int i=0;
        int j=nums.length-1;
        while(i<j) {
            int x=nums[i]+nums[j];
            if(x<target) {
                ++i;
            }else if(x>target) {
                j--;
            }else {
                return new int[] {i+1,j+1};
            }
        }
        return null;
    }
    public static void main(String[] args) {
        int[] A= {0,2,5,4,6,3,7,8};
        int[] result=twoSum(A, 9);
        if(result!=null) {
            System.out.println(result[0]+" "+result[1]);
        }

    }
}

  • 结果
    7 2
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容