1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].My answer:
class Solution { 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[i] == target - nums[j]) return new int[]{i, j}; continue; } return null; } }Others: 使用hashmap,遍历数组,将target-arr[i]插入hashmap,判断下一个元素是否在hashmap中
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步