学习1:c++基础
学习了数据类型 运算符 程序流程结构
学了几个简单编程问题:
(1):猜数字
生成一个随机数,让用户猜,并告知大了还是小了,注意要添加随机数种子,防止每次随机数都一样,作用利用当前系统时间生成随机数
srand((unsigned int)time(NULL));
(2):水仙数
注意个位 十位 百位的表示方法
(3):逢七必过
注意if语句里判断语句
(4):99乘法表(嵌套语句)
(5):副本难度(switch-case语句)
代码如下:
cpp
#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>
#include <string>
using namespace std;
#include <ctime>
int main() {
//1、在switch 语句中使用break
cout << "请选择您挑战副本的难度:" << endl;
cout << "1、普通" << endl;
cout << "2、中等" << endl;
cout << "3、困难" << endl;
int num = 0;
cin >> num;
switch (num)
{
case 1:
cout << "您选择的是普通难度" << endl;
break;
case 2:
cout << "您选择的是中等难度" << endl;
break;
case 3:
cout << "您选择的是困难难度" << endl;
break;
}
system("pause");
return 0;
}
//int chengfabiao() {
// for (int i = 1; i < 10; i++)
// {
// for (int j = 1; j <= i; j++) {
// cout << j << "*" << i << "=" << j * i << " ";
// }
// cout << endl;
// }
//}
//int xingtu() {
// //利用嵌套循环实现星图
//
// for (int i = 0; i < 10; i++)
// {
// //内层循环
// for (int j = 0; j < 10; j++)
// {
// cout << "* ";
// }
// cout << endl;
// }
//
//
//}
//int qiaozhuozi() {
// //逢七过
//
// for (int num = 1; num <= 100; num++) {
// if (num % 7 == 0 || num % 10 == 7 || num / 10 == 7) {
//
// cout << "敲桌子" << endl;
// }
// else {
// cout << num << endl;
// }
// }
//
//}
//int shuixianhua_number() {
// int num = 100;
//
// do
// {
// int a = 0;
// int b = 0;
// int c = 0;
// //获得个位%10
// //获取十位 /10后再%10
// //获取百位 %100
// a = num % 10;
// b = num / 10 % 10;
// c = num / 100;
//
// if (a*a*a + b*b*b +c*c*c == num) {
// cout << num << endl;
//
// }
// num++;
// return 0;
// } while (num <=999);
//
//
//}
//
//int caishuzi() {
//
// //添加随机数种子,防止每次随机数都一样,作用利用当前系统时间生成随机数
// srand((unsigned int)time(NULL));
//
// //生成随机数
// int num = rand() % 100 + 1;
// /*cout << num << endl;*/
//
// int val = 0;
//
//
// while (1) {
// cin >> val;
// if (val > num)
// {
// cout << "猜测过大" << endl;
// }
// else if (val < num) {
// cout << "猜测过小" << endl;
// }
// else
// {
// cout << "恭喜你猜对了" << endl;
// break;
// }
// }
// return 0;
//
//}
二分查找:例题为leetcode 704题二分查找,同时查看视频代码随想录:https://www.bilibili.com/video/BV1fA4y1o715?t=0.4
题目如下
给定一个
n个元素有序的(升序)整型数组nums和一个目标值target,写一个函数搜索nums中的target,如果target存在返回下标,否则返回-1。你必须编写一个具有
O(log n)时间复杂度的算法。示例 1:
输入: nums = [-1,0,3,5,9,12], target = 9 输出: 4 解释: 9 出现在 nums 中并且下标为 4示例 2:
输入: nums = [-1,0,3,5,9,12], target = 2 输出: -1 解释: 2 不存在 nums 中因此返回 -1
我写的代码如下:参考的是王道的二叉查找法
cpp
class Solution {
public:
int search(vector<int>& nums, int target) {
int left = 0;
int right = nums.size() - 1;
while(left<=right){
int middle = (left + right) / 2;
if(left <= right && target < nums[middle] ) right = middle - 1;
else if(left <= right && target > nums[middle] ) left = middle + 1;
else return middle;
}
return -1;
}
};
参考代码
