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。

  • 相关阅读:
    .NETCore_初探
    .NETCore_生成实体
    架构碎屑
    Helper
    26.【转载】挖洞技巧:绕过短信&邮箱轰炸限制以及后续
    25.【转载】挖洞技巧:支付漏洞之总结
    24.【转载】挖洞技巧:信息泄露之总结
    5.Windows应急响应:挖矿病毒
    4.Windows应急响应:勒索病毒
    3.Windows应急响应:蠕虫病毒
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4066299.html
Copyright © 2011-2022 走看看