Java二叉搜索树与数组查找的方法
本篇内容介绍了“Java二叉搜索树与数组查找的方法”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
题目一

解法
/***Definitionforabinarytreenode.*publicclassTreeNode{*intval;*TreeNodeleft;*TreeNoderight;*TreeNode(){}*TreeNode(intval){this.val=val;}*TreeNode(intval,TreeNodeleft,TreeNoderight){*this.val=val;*this.left=left;*this.right=right;*}*}*/classSolution{intans;intpre;publicintminDiffInBST(TreeNoderoot){ans=Integer.MAX_VALUE;pre=-1;method(root);returnans;}publicvoidmethod(TreeNoderoot){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);}}
题目二

解法
classSolution{publicintdominantIndex(int[]nums){intf=Integer.MIN_VALUE;intfi=0;ints=Integer.MIN_VALUE;intsi=0;for(inti=0;i<nums.length;i++){if(nums[i]>f){s=f;f=nums[i];fi=i;}elseif(nums[i]>s){s=nums[i];}}if(nums.length==1)return0;if(2*s<=f)returnfi;return-1;}}
题目三

解法
classSolution{publicintrepeatedNTimes(int[]nums){intn=nums.length/2;HashMap<Integer,Integer>map=newHashMap<Integer,Integer>();for(intkey:nums){if(map.containsKey(key)){map.put(key,map.get(key)+1);if(map.get(key)==n){returnkey;}}else{map.put(key,1);}}return0;}}
题目四

解法
classSolution{publicbooleanuniqueOccurrences(int[]arr){int[]nums=newint[2000];for(inti=0;i<arr.length;i++){nums[arr[i]+1000]+=1;}HashSet<Integer>set=newHashSet<Integer>();for(inti=0;i<nums.length;i++){if(nums[i]==0)continue;if(!set.add(nums[i])){returnfalse;}else{set.add(nums[i]);}}returntrue;}}
“Java二叉搜索树与数组查找的方法”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注恰卡编程网网站,小编将为大家输出更多高质量的实用文章!