• 167


    解法1,利用二分查找,对第一个i,去剩下的有序数组中查找target-numbers[i]

    class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] res=new int[2];
            for(int i=0;i<numbers.length;i++)
            {
                int find=binarySearch(numbers,i+1,numbers.length-1,target-numbers[i]);
                if(find!=-1)
                {
                    res[0]=i+1;
                    res[1]=find+1;
                }
            }
            return res;
        }
        public int binarySearch(int[] arr,int l,int r,int target)
        {
            if(l<=r)
            {
                 int mid=l+(r-l)/2;
                if(arr[mid]==target)
                    return mid;
                 else if(arr[mid]>target)
                     return binarySearch(arr,l,mid-1,target);
                else
                    return binarySearch(arr,mid+1,r,target);
            }
             else
                 return -1;
            
        }
    }

    //解法2,碰撞指针

    class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] res=new int[2];
            int i=0,j=numbers.length-1;
            while(i<j)
            {
                if(numbers[i]+numbers[j]==target)
                {
                    res[0]=i+1;
                    res[1]=j+1;
                    break;
                }
                else if(numbers[i]+numbers[j]<target)
                    i++;
                else
                    j--;
            }
            return res;
        }
    }

  • 相关阅读:
    在asp.net项目中使用winform窗口
    href="#"是什么意思呢? (转)
    在asp.net webservice中如何使用session(转载)
    ASP.NET 2.0 新追加控件ImageMap介绍(转)
    SEO是什么?
    推荐60个jQuery插件(转)
    asp.net webform 与asp.net mvc 混合开发项目总结
    获取SqlDataReader的列名
    梯度下降法 Method of steepest descent.
    蒙特卡洛算法
  • 原文地址:https://www.cnblogs.com/cold-windy/p/11252916.html
Copyright © 2020-2023  润新知