开发者社区> 问答> 正文

给定一个整数数组和一个整数,返回两个数组的索引

题目:给定一个整数数组和一个整数,返回两个数组的索引,这两个索引指向的数字的加和等于指定的整数。需要最优的算法,分析算法的空间和时间复杂度

展开
收起
Runt 2020-04-14 18:30:02 7490 0
2 条回答
写回答
取消 提交回答
  • 有点尴尬唉 你要寻找的东西已经被吃掉啦!

    public static int[] twoSum(int[] numbers, int target) { int i = 0, j = numbers.length - 1;

        while (i != j) {
            if (numbers[i] + numbers[j] == target) {
                return new int[]{i + 1, j + 1};
            }
    
            if (numbers[i] + numbers[j] < target) {
                i++;
                continue;
            }
    
            if (numbers[i] + numbers[j] > target) {
                j--;
                continue;
            }
        }
    
        return new int[]{i, j};
    }
    
    2020-04-15 22:52:27
    赞同 展开评论 打赏
  • 参考答案:

    public int[] twoSum(int[] nums, int target) {
        if(nums==null || nums.length<2)
            return new int[]{0,0};
     
        HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0; i<nums.length; i++){
            if(map.containsKey(nums[i])){
                return new int[]{map.get(nums[i]), i};
            }else{
                map.put(target-nums[i], i);
            }
        }
     
        return new int[]{0,0};
    }
    

    分析:空间复杂度和时间复杂度均为 O(n)

    2020-04-14 18:30:34
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载