劍指Offer之Java算法習(xí)題精講二叉搜索樹與數(shù)組查找
更新時間:2022年03月18日 14:57:41 作者:明天一定.
跟著思路走,之后從簡單題入手,反復(fù)去看,做過之后可能會忘記,之后再做一次,記不住就反復(fù)做,反復(fù)尋求思路和規(guī)律,慢慢積累就會發(fā)現(xiàn)質(zhì)的變化
題目一

?解法
/**
* 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;
}
}
到此這篇關(guān)于劍指Offer之Java算法習(xí)題精講二叉搜索樹與數(shù)組查找的文章就介紹到這了,更多相關(guān)Java 二叉搜索樹內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:
- 劍指Offer之Java算法習(xí)題精講鏈表與字符串及數(shù)組
- 劍指Offer之Java算法習(xí)題精講二叉搜索樹與數(shù)組查找
- 劍指Offer之Java算法習(xí)題精講數(shù)組與字符串題
- 劍指Offer之Java算法習(xí)題精講N叉樹的遍歷及數(shù)組與字符串
- 劍指Offer之Java算法習(xí)題精講數(shù)組與字符串
- 劍指Offer之Java算法習(xí)題精講數(shù)組與列表的查找及字符串轉(zhuǎn)換
- 劍指Offer之Java算法習(xí)題精講字符串操作與數(shù)組及二叉搜索樹
- 劍指Offer之Java算法習(xí)題精講數(shù)組與二叉樹
相關(guān)文章
mybatis-plus查詢無數(shù)據(jù)問題及解決
這篇文章主要介紹了mybatis-plus查詢無數(shù)據(jù)問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12
Java基礎(chǔ)知識精通數(shù)組的內(nèi)存分析
數(shù)組對于每一門編程語言來說都是重要的數(shù)據(jù)結(jié)構(gòu)之一,當(dāng)然不同語言對數(shù)組的實現(xiàn)及處理也不盡相同。Java?語言中提供的數(shù)組是用來存儲固定大小的同類型元素2022-04-04
Logger.getLogger()與LogFactory.getLog()的區(qū)別詳解
LogFactory來自common-logging包。如果用LogFactory.getLog,你可以用任何實現(xiàn)了通用日志接口的日志記錄器替換log4j,而程序不受影響2013-09-09
Java多線程并發(fā)編程 Synchronized關(guān)鍵字
現(xiàn)有一成員變量 Test,當(dāng)線程 A 調(diào)用 Test 的 synchronized 方法,線程 A 獲得 Test 的同步鎖,同時,線程 B 也去調(diào)用 Test 的 synchronized 方法,此時線程 B 無法獲得 Test 的同步鎖,必須等待線程 A 釋放 Test 的同步鎖才能獲得從而執(zhí)行對應(yīng)方法的代碼2017-05-05

