一种使用树结构优化switch语句的方法

介绍

在日常 装B 写代码中会经常用到if else if语句如:

if(1){
		
	}
	else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}else if(1){
		//TODO
	}

非常的麻烦,而且慢,我们可以用二分的思想去查找,如:

#include <iostream>
using namespace std;
int main() {
	int n;
	cin>>n;
	if(n<50){
		if(n<25){
			if(n<15){
				cout<<"<15";
			}
			else{
				cout<<">15";
			}
		}
		else{
			if(n>35){
				cout<<"666";
			}
			else{
				cout<<"666";
			}
		}
	}
	else{
		if(n>75){
			if(n>85){
				cout<<"<85";
			}
			else{
				cout<<">85";
			}
		}
		else{
			if(n>15){
				cout<<"666";
			}
			else{
				cout<<"666";
			}
		}
	}
	return 0;
}

这样我们就可以在O(logn)的时间复杂度去执行有n种可能的代码。

swith语句的条件非数字或没有固定范围时的解决方法

如果是字符串的话可以像字典树一样遍历到最后。这样也有优化。

思路核心

就是用二分的思想进行优化,减少判断,如果有其他思路欢迎评论!感谢!!!

posted @   mcr130102  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
请不要抄袭任何人的博客,这是对一名开发者最基本的尊重。
点击右上角即可分享
微信分享提示
如今我对自己故乡,像来往匆匆的过客。