哈希表
两数之和
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
struct no{
int key=0;
int value;
}hash[1000];
int nums[4]={2,7,11,15};
int t=9; // 目标和
int i;
for(i=0;i<4;i++){
if(hash[t-nums[i]].key==0){ // 如果所需的匹配元素哈希表中没有
hash[nums[i]].key=1; // 将当前遍历元素存入哈希表
hash[nums[i]].value=i; // 存放此元素下标
}
else{ // 如果有,说明找到了
printf("%d %d",hash[nums[i]].value,hash[t-nums[i]].value);
return 0;
}
}
单调栈
最大矩形
给定 n 个非负整数,用来表示柱状图中各个柱子的高度。每个柱子彼此相邻,且宽度为 1 。
求在该柱状图中,能够勾勒出来的矩形的最大面积。
代码
int arr[8]={0,2,1,5,6,2,3,0}; //柱形图高度数组(这里默认对每个数组首位加0)
int q[8]={0}; //栈
int i,top=0; //栈顶
int sum=0,h,w,left,right;
for(i=1;i<9;i++){
if(arr[i]>arr[q[top]]){
q[++top]=i; // 将当前遍历元素下标加入栈
}
else if(arr[i]==arr[q[top]]){
q[top]=i; // 替换当前栈顶下标
}
else {
while(top>=0&&arr[i]<arr[q[top]]){
int t=q[top]; //存储栈顶下标
top--; // 出栈
if(top>=0){
left=q[top];
right=i;
h=arr[t];
w=right-left+1;
sum=max(sum,h*w);
}
}
q[++top]=i; // 将当前遍历元素入栈
}
}