zoukankan      html  css  js  c++  java
  • leetcode:两个数的和||

    两个数的和||

    给定一个排序数组,求出其中两个数的和等于指定target时,这两个数在原始数组中的下标,返回的下标从1开始

    解题

    原始数组已经是升序的,找出其中两个数的和等于target

    定义两个指针,left right

    计算x = num[left] + num[right] 的值

    等于target 返回下标

    小于target,说明需要增大这两个数,然后num[right] 已经是最大的数了,我们只有增加num[left],通过left++ 来增加

    大于target right--

    public class Solution {
        public 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(i> target)
                    j--;
                else
                    return new int[]{i+1,j+1};
            }
            return null;
        }
    }

    说明:LeetCode是收费才能做的题目

  • 相关阅读:
    Webform服务器控件调用JS
    Webfrom基础知识
    Webform用户控件
    数组练习
    整理
    SVN分支与合并
    根据经纬度,获取两点间的距离
    简单Bat文件编写
    Maven Android使用一
    Maven环境配置
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5448272.html
Copyright © 2011-2022 走看看