zoukankan      html  css  js  c++  java
  • 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

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
    //   int a[] = {0,0};
    //     int len=numbers.length;
    //     int mid,left,right;
    //     for(int i=0;i<len;i++){
    //         for(int j=0;j<i;j++){
    //             if(numbers[i]+numbers[j]==target){
    //                 a[0]=j+1;
    //                 a[1]=i+1;
    //                 return a;
    //             }
    //         }
    //     }
    //         return null;
    
    //第一种暴力解法通过可能是因为case的问题 O(n^2)     第二个for循环换成for(int j=i+1;j<len;j++)就超时了
    //用HashMap的原因是containsKey查找效率高O(nlogn)
            int[] a = new int[2];
            HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
            for(int i=0;i<numbers.length;i++){
                if(map.containsKey(target-numbers[i])){
                    a[1]=i+1;
                    a[0]=map.get(target-numbers[i])+1;
                    return  a;
                }
                map.put(numbers[i], i);
            }
            return  null;
            
        }
    }
  • 相关阅读:
    Unity SceneManager 对场景的操作
    Unity [Tooltip("")]
    Unity WWW下载图片并保存到Unity的Assets下
    C# 集合
    C# 枚举与switch用法
    C# String.Format方法
    C# Thread类 线程优先级
    Unity Gizmos可视化辅助工具
    anacanda
    异常和错误
  • 原文地址:https://www.cnblogs.com/gaoxiangde/p/4210291.html
Copyright © 2011-2022 走看看