zoukankan      html  css  js  c++  java
  • #1_两数之和

    Category Difficulty Likes Dislikes
    algorithms Easy (47.92%) 7893 -

    我的答案

    public int[] twoSum(int[] nums, int target) {
        int i, j;
        int[] res = new int[2];
        for(i = 0; i < nums.length; i++){
            for(j = i + 1; j < nums.length; j++){
                if(nums[i] + nums[j] == target){
                    res[0] = i;
                    res[1] = j;
                    return res;
                }
            }
        }
        return res;
    }
    

    解题思路

    遍历每个元素,并查找是否有一个元素与它相加等于 target

    答案分析

    时间复杂度 O(n2)

    空间复杂度 O(1)

    缺少异常处理

    参考方案

    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            int tmp = target - nums[i];
            if(map.containsKey(tmp)){
                return new int[] {map.get(tmp),i}; 
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No Two Sum Solution");
    }
    

    时间复杂度 O(n)

    空间复杂度 O(n)

    备注

    • HashMap 的 API
    void                 clear()
    Object               clone()
    boolean              containsKey(Object key)
    boolean              containsValue(Object value)
    Set<Entry<K, V>>     entrySet()
    V                    get(Object key)
    boolean              isEmpty()
    Set<K>               keySet()
    V                    put(K key, V value)
    void                 putAll(Map<? extends K, ? extends V> map)
    V                    remove(Object key)
    int                  size()
    Collection<V>        values()
    



  • 相关阅读:
    单个对象的内存管理分析
    在eclipse中引入jquery.js文件报错的解决方案
    ajax复习
    jquery介绍
    ajax调试小技巧
    ajax实现聊天室功能
    ajax(2)
    ajax经典案例--省市联动
    ajax技术返回json如何处理
    ajax如何处理返回的数据格式是xml的情况
  • 原文地址:https://www.cnblogs.com/mdz3201/p/leetcode_1.html
Copyright © 2011-2022 走看看