zoukankan      html  css  js  c++  java
  • 每日一题(算法)

    题目:两数之和

    给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

    解法一(双重for循环)

    时间复杂度O(n2)

    空间复杂度O(1)

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] index = new int[2];
            out:
            for(int i=0;i<nums.length;i++){
                int one = nums[i];
                for(int j=i+1;j<nums.length;j++){
                    int two = nums[j];
                    int total = one + two;
                    if (total == target){
                        index[0] = i;
                        index[1] = j;
                        break out;
                    }
                }
            }
            System.out.println(index);
            return index;
        }
    }

    解法二(hashMap)

    时间复杂度O(n)

    空间复杂度O(n)

    解法二是采用了空间换时间的方式

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            for(int i = 0; i < nums.length; i++){
                if(map.containsKey(target-nums[i])){
                    return new int[]{map.get(target-nums[i]),i};
                }
                map.put(nums[i],i);
    
            }
            return new int[0];
        }
    }
  • 相关阅读:
    Jmeter断言设置
    jmeter设置自动启动时间
    jmeter用命令行运行jmx脚本
    jmeter多用户并发压力测试(导入文件)
    Fiddler导出接口抓包数据
    postman和postwoman
    UVa10561
    UVa11859
    Ferguson游戏
    UVa11916
  • 原文地址:https://www.cnblogs.com/libinhyq/p/14871277.html
Copyright © 2011-2022 走看看