zoukankan      html  css  js  c++  java
  • 【leetcode】1. Two Sum

    题目描述:

    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

    解题思路:

    这道题比较简单,可以把数组复制,按大小排列,找到满足条件的两个数后倒推找回他们在原数组中的位置即可。但是在编码过程中,要注意区分两个找到的数值相等的情况,否则会返回两个相同值。

     1 public class Solution {
     2        public static int[] twoSum(int[] nums, int target) {
     3         int[] nums1=Arrays.copyOf(nums, nums.length);
     4         Arrays.sort(nums1);
     5         int[] result = new int[2];
     6         int start = 0;
     7         int end = nums1.length-1;
     8         while(start<end){
     9             if(nums1[start]+nums1[end]==target){
    10                 //要注意区分两个找到的数值相等的情况
    11                 if(nums1[start]!=nums1[end]){
    12                 for(int i=0;i<nums.length;i++){
    13                     if(nums[i]==nums1[start]){
    14                         result[0]=i;
    15                     }
    16                     if(nums[i]==nums1[end]){
    17                         result[1]=i;
    18                     }
    19                 }
    20                 }
    21                 if(nums1[start]==nums1[end]){
    22                     boolean found=false;
    23                     for(int i=0;i<nums.length;i++){
    24                         if(!found){
    25                             if(nums[i]==nums1[start]){
    26                                 result[0]=i;
    27                                 found=true;
    28                             }
    29                         }
    30                         else{
    31                             if(nums[i]==nums1[end]){
    32                                 
    33                                 result[1]=i;
    34                                 break;
    35                             }
    36                         }
    37                         
    38                     }
    39                 }
    40                 return result;
    41             }
    42             else if(nums1[start]+nums1[end]>target){
    43                 end--;
    44             }
    45             else{
    46                 start++;
    47             }
    48         }
    49         return result;
    50     }
    51 }
  • 相关阅读:
    [转]王垠的过去和现状
    支持向量机(SVM)基础
    C语言编程心得
    Fortran学习心得
    gdb使用心得
    大道至简第一章读后感
    第一个音符
    Exercise 1.20 最大公约数算法
    Exercise 1.19 Fast Fibonacci
    Exercise 1.16 1.17 1.18
  • 原文地址:https://www.cnblogs.com/godlei/p/5559597.html
Copyright © 2011-2022 走看看