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 }
  • 相关阅读:
    poj3984 迷宫问题(简单搜索+记录路径)
    substr
    poj3087 Shuffle'm Up
    学生管理系统
    win10配置gcc编译环境
    poj3278 Catch That Cow
    将字符串str1复制为字符串str2的三种解决方法
    poj2251 Dungeon Master
    cf 410
    7.20 Codeforces Beta Round #8
  • 原文地址:https://www.cnblogs.com/godlei/p/5559597.html
Copyright © 2011-2022 走看看