Java 二叉搜索树
明天一定. 人气:0题目一
解法
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int ans; int pre; public int minDiffInBST(TreeNode root) { ans = Integer.MAX_VALUE; pre = -1; method(root); return ans; } public void method(TreeNode root){ if(root==null) return; method(root.left); if(pre==-1){ pre = root.val; }else{ ans = Math.min(ans,root.val-pre); pre = root.val; } method(root.right); } }
题目二
解法
class Solution { public int dominantIndex(int[] nums) { int f = Integer.MIN_VALUE; int fi = 0; int s = Integer.MIN_VALUE; int si = 0; for(int i = 0; i<nums.length;i++){ if(nums[i]>f){ s = f; f = nums[i]; fi = i; }else if(nums[i]>s){ s = nums[i]; } } if(nums.length==1) return 0; if(2*s<=f) return fi; return -1; } }
题目三
解法
class Solution { public int repeatedNTimes(int[] nums) { int n = nums.length/2; HashMap<Integer,Integer> map =new HashMap<Integer,Integer>(); for(int key : nums){ if(map.containsKey(key)){ map.put(key,map.get(key)+1); if(map.get(key)==n){ return key; } }else{ map.put(key,1); } } return 0; } }
题目四
解法
class Solution { public boolean uniqueOccurrences(int[] arr) { int[] nums = new int[2000]; for(int i =0;i<arr.length;i++){ nums[arr[i]+1000]+=1; } HashSet<Integer> set =new HashSet<Integer>(); for(int i =0;i<nums.length;i++){ if(nums[i]==0) continue; if(!set.add(nums[i])){ return false; }else{ set.add(nums[i]); } } return true; } }
加载全部内容