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

     1 public class Solution {
     2     public int[] twoSum(int[] numbers, int target) {
     3         int[] sorted = numbers.clone();
     4         Arrays.sort(sorted);
     5         int l = 0, r = numbers.length - 1;
     6         int sum = 0;
     7         while (l < r) {
     8             sum = sorted[l] + sorted[r];
     9             if (sum == target) {
    10                 int i=0,j=0;
    11                 for (int k = 0; k < numbers.length; k++) {
    12                     if (numbers[k]==sorted[l]&& i==0) i=k+1;
    13                     if (numbers[k]==sorted[r]) j=k+1;
    14                 }
    15                 return new int[]{Math.min(i,j),Math.max(i,j)};
    16             }
    17             if (sum > target) {
    18                 r--;
    19                 continue;
    20             }
    21             if (sum < target) {
    22                 l++;
    23                 continue;
    24             }
    25         }
    26         return null;
    27     }
    28 }
  • 相关阅读:
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
    第六周实验总结&学习总结
    关于我
    各种公告

    笔记 综合
    多项式全家桶
    FFT,NTT 笔记
    省选复习
  • 原文地址:https://www.cnblogs.com/birdhack/p/4116037.html
Copyright © 2011-2022 走看看