centos7下Jenkins管理员admin密码
986 2023-04-03 02:36:41
暴力解法
:通过两个for循环逐步遍历,判断是否有符合条件的答案class Solution { public int[] twoSum(int[] nums, int target) { int[] dp = new int[2]; for(int i = 0 ;i <nums.length;i++){ if(nums[i]>Math.abs(target)){ continue; }else{ for(int j = i+1;j<nums.length;j++){ if(target == nums[i]+nums[j]){ dp[0] = i; dp[1] = j; } } } } return dp; }}
class Solution { public int[] twoSum(int[] nums, int target) { int[] dp = new int[2]; for(int i = 0 ;i <nums.length;i++){ for(int j = i+1;j<nums.length;j++){ if(target == nums[i]+nums[j]){ dp[0] = i; dp[1] = j; } } } return dp; } }
哈希表法
:先将数据存入哈希表中,再使用目标值依次减去数组中的数据,再从哈希表中找是否有符合条件的值,如果有,将下标传给result数组
,返回结果。class Solution { // HashMap // N is the size of nums // Time Complexity: O(N) // Space COmplexity: O(N) public int[] twoSum(int[] nums, int target) { int[] result = new int[2]; //定义hashMap HashMap<Integer,Integer> map = new HashMap<>(); for(int i=0;i < nums.length;i++){ //将所有数据存入hash表中 map.put(nums[i],i); } //使用目标值减去数组中的值,查看表中是否有符合条件的值就返回 for(int j=0;j < nums.length; j++){ int diff = target - nums[j]; if(map.containsKey(diff)&&map.get(diff)!=j){ result[0] = j; result[1] = map.get(diff); return result; } } return result; }}