美文网首页
对撞指针

对撞指针

作者: 少寨主的互联网洞察 | 来源:发表于2018-10-02 16:11 被阅读0次
    对撞指针.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

    相关文章

      网友评论

          本文标题:对撞指针

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