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。

  • 相关阅读:
    实验五 shell脚本编程
    实验四 Linux系统C语言开发环境学习
    实验三 Linux系统用户管理及VIM配置
    实验二 Linux系统简单文件操作命令
    实验一 Linux系统与应用准备
    实验八 进程间通信
    实验七 信号
    实验六 进程基础
    实验五 shell脚本编程
    实验四 Linux系统搭建C语言编程环境
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4066299.html
Copyright © 2011-2022 走看看