leetcode1.2(两数的和与目标值,不考虑溢出反转整数)

it2023-07-23  70

1. 在数组中找出和为一个目标值的两个整数,返回两个整数的下标

import java.util.HashMap; public class HeWeiMuBiaoZhi { public static void main(String[] args) { int[] arr = {2, 3, 4, 5, 6}; int[] a = twoSum(arr, 7); for (int bianli : a){ System.out.println(bianli); } } public static int[] twoSum(int[] nums,int target){ HashMap<Integer, Integer> hashmap = new HashMap<>(); // 创建哈希表 for (int i=0; i<nums.length; i++){ // 遍历数组每一个元素 /** * ①i=0 hashmap !containskey(7-2) 执行else 哈希表 key:2 -> value:0 * ②i=1 hashmap !containskey(7-3) 执行else 哈希表 key:2 -> value:0 key:3 -> value:1 * ③i=2 hashmap containskey(7-4) 执行if {hashmap.get(3),2} => {value:1,2} => {1,2} */ if (hashmap.containsKey(target - nums[i])) { // 如果哈希表中包括 (目标值-当前元素值),说明已找到这两个数 return new int[]{hashmap.get(target-nums[i]),i}; // 返回创建新的数组,存放 用哈希表通过获取键值key映射出的value值,和当前元素下标 }else{ // 如果哈希表中找不到 目标值-当前元素值,例如第一次循环哈希表为空表, hashmap.put(nums[i],i); // 一定会将key(第一个元素值)=2,value(对应的下标)=0,存放到哈希表中 } } return new int[0]; // 返回一个数组 } }

2.反转整数(不考虑溢出)

参照另一博文:判断回文数

public class FanZhuan { public static void main(String[] args) { int result = reverse(12345); System.out.println(result); } public static int reverse(int x){ int res=0; while (x != 0) { res = res*10+x%10; // 参照判断回文数 x/=10; } return res; } }

 

最新回复(0)