• LeetCode_167. Two Sum II


    167. Two Sum II - Input array is sorted

    Easy

    Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.

    Note:

    • Your returned answers (both index1 and index2) are not zero-based.
    • You may assume that each input would have exactly one solution and you may not use the same element twice.

    Example:

    Input: numbers = [2,7,11,15], target = 9
    Output: [1,2]
    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
    package leetcode.easy;
    
    public class TwoSumIIInputArrayIsSorted {
    	@org.junit.Test
    	public void test() {
    		int[] numbers = { 2, 7, 11, 15 };
    		int target = 9;
    		System.out.println(twoSum(numbers, target));
    	}
    
    	public int[] twoSum(int[] numbers, int target) {
    		for (int i = 0; i < numbers.length - 1; i++) {
    			for (int j = i + 1; j < numbers.length; j++) {
    				if (numbers[i] + numbers[j] == target) {
    					return new int[] { i + 1, j + 1 };
    				}
    			}
    		}
    		return new int[] { 0, 0 };
    	}
    }
    
  • 相关阅读:
    mysql是如何启动的?
    qt终于安装成功
    随笔
    博客首写
    为什么你预约不了政府特供口罩-太难了
    jQuery 选择器(转)
    [JS]Cookie精通之路
    存储过程分页 简单列子
    泛型集合List<T> Dictionary<K,V>
    数据绑定控件
  • 原文地址:https://www.cnblogs.com/denggelin/p/11676851.html
Copyright © 2020-2023  润新知