zoukankan      html  css  js  c++  java
  • [Leetcode] Two Sum

    Given an array of integers, 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. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    Solution:

     1 public class Solution {
     2     public int[] twoSum(int[] numbers, int target) {
     3         int[] result = { -1, -1 };
     4         if (numbers.length < 2)
     5             return result;
     6         int[] copyNumbers = numbers.clone();
     7         Arrays.sort(copyNumbers);
     8         int low = 0;
     9         int high = copyNumbers.length - 1;
    10         int num1 = 0, num2 = 0;
    11         while (low < high) {
    12             int temp = copyNumbers[low] + copyNumbers[high];
    13             if (temp < target)
    14                 low++;
    15             else if (temp > target)
    16                 high--;
    17             else {
    18                 num1 = copyNumbers[low];
    19                 num2 = copyNumbers[high];
    20                 break;
    21             }
    22         }
    23         for (int i = 0; i < numbers.length; ++i) {
    24             if (numbers[i] == num1 || numbers[i] == num2) {
    25                 if (result[0] == -1)
    26                     result[0] = i + 1;
    27                 else
    28                     result[1] = i + 1;
    29             }
    30         }
    31         return result;
    32     }
    33 }

    这里需要注意的是:

    要返回的是index,所以得1.在复制后的copyNum里找到值,2. 在原num数组里通过值找到index。

  • 相关阅读:
    XML和JSON的区别
    浏览器渲染和服务器渲染区别
    存储过程
    对象关系映射(ORM)
    GitHub和SVN的区别
    WEB网站常见受攻击方式及解决办法
    同源与跨域
    java常用API之DateFormat
    java常用API之Date类
    面型对象之匿名对象
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4066299.html
Copyright © 2011-2022 走看看