每日一题-数组 leetcode1

241 阅读2分钟

一、题目描述

二、提交代码

import java.util.Arrays;
import java.util.Scanner;
class Solution{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入数组:");
        String[] string = sc.nextLine().split(" ");
        int[] nums = new int[string.length];
        for(int i =0;i<string.length;i++){
            nums[i] = Integer.parseInt(string[i]);
        }
        System.out.println("请输入目标数:");
        int target = sc.nextInt();
        Solution solution = new Solution();
        int[] result = solution.twoSum(nums,target);
        System.out.println(Arrays.toString(result));
    }
    public int[] twoSum(int[] nums,int target){
        for(int i =0;i<nums.length;i++){
            for(int j = i+1;j<nums.length;j++){
                if(nums[j] == target - nums[i]){
                    return new int[]{i,j};
                }
            }
        }
        return new int[]{-1,-1};
    } 
}
  1. 定义接受用户输入的类的对象需要import java.util.Scanner;,注意Scanner 中的S需要大写

  2. length 用来获取数组的长度,调用对象属性; length() 用来获取字符串的长度,调用方法; size() 用来获取泛型集合的长度,调用方法

  3. Integer.parseInt()方法可以将字符串类型数据转换为整型,Integer类的parseInt()方法。

4. Arrays的toString()方法,可以将数组类型的数据转换为字符串进行输出。需要事先import java.util.Arrays;

  1. new int[]{} ,即时定义新的数组。

存在的问题

  1. 时间复杂度为O(n^2)。

三、优解代码

import java.util.HashMap;
class solution{
    public int[] twoSum(int[] nums,int target){
        HashMap<Integer,Integer> hashMap = new HashMap();
        for(int i=0;i<nums.length;i++){
            if(hashMap.containsKey(target - nums[i])){
                return new int[]{hashMap.get(target - nums[i]),i};
            }
            hashMap.put(nums[i],i);
        }
        return new int[]{-1,-1};
    }
}
  1. 定义HashMap,需要事先import java.util.HashMap;
  2. 实例化HashMap,需要声明HashMap<Integer,Integer> 代码:

HashMap<Integer,Integer> hashMap = new HashMap();

  1. HashMap 的方法containsKey(Object key)可以判断HashMap中是否包含特定键key;
  2. HashMap 的方法containsValue(Object value)可以判断HashMap中是否包含特定值value;
  3. HashMap 的方法put(key,value)可以添加键值对元素;

四、优解特点

  1. 时间复杂度为O(n);
  2. 算法实现上,实例化HashMap,将数组中的元素索引作为键值对存在HashMap中,在遍历数组元素时,巧妙调用containsKey()方法判断数组中是否包含结果元素(target - 当前元素),如果存在的话,通过HashMap的get()得到结果元素索引;
  3. HashMap通过进行逻辑的判断,通过存储索引,在一次遍历的时候便可以方便地得到索引。