leetcode 初级算法
从认真开始做题到完成初级算法,一共经过了大概两个月的时间。这个过程学到了很多东西,巩固复习了很多接近遗忘的知识,还扩展学习到了一些,感觉有了一种新的思维模式。
在这里将这些题目总结,方便日后查阅。
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
//输入方法
//输入包括两个正整数a,b(1 <= a, b <= 10^9),输入数据包括多组。
//1 5
//10 20
int main() {
int a, b;
while (cin >> a >> b) {
cout << a + b << endl;
}
return 0;
}
//输入第一行包括一个数据组数t(1 <= t <= 100)
//接下来每行包括两个正整数a, b(1 <= a, b <= 10 ^ 9)
//2
//1 5
//10 20
int main() {
int t;
cin >> t;
for (int i = 0; i < t; ++i) {
int a, b;
cin >> a >> b;
cout << a + b << endl;
}
return 0;
}
//输入包括两个正整数a, b(1 <= a, b <= 10 ^ 9), 输入数据有多组, 如果输入为0 0则结束输入
//1 5
//10 20
//0 0
int main() {
int a, b;
while (cin >> a >> b) {
if (!a && !b)
break;
cout << a + b << endl;
}
return 0;
}
//输入数据包括多组。
//每组数据一行, 每行的第一个整数为整数的个数n(1 <= n <= 100), n为0的时候结束输入。
//接下来n个正整数, 即需要求和的每个正整数。
//4 1 2 3 4
//5 1 2 3 4 5
//0
int main()
{
int n;
int m;
while (cin >> n)
{
if (!n)
break;
else
{
int sum = 0;
for (int i = 0; i> m;
sum += m;
}
cout << sum << endl;
}
}
return 0;
}
//输入的第一行包括一个正整数t(1 <= t <= 100), 表示数据组数。
//接下来t行, 每行一组数据。
//每行的第一个整数为整数的个数n(1 <= n <= 100)。
//接下来n个正整数, 即需要求和的每个正整数。
//2
//4 1 2 3 4
//5 1 2 3 4 5
int main()
{
int a, b, c, sum;
while (cin >> a)
{
for (int i = 0; i < a; i++)
{
cin >> b;
for (int j = 0; j < b; j++)
{
cin >> c;
sum += c;
}
cout << sum << endl;
sum = 0;
}
}
return 0;
}
//输入数据有多组, 每行表示一组输入数据。
//每行不定有n个整数,空格隔开。(1 <= n <= 100)。
//1 2 3
//4 5
//0 0 0 0 0
int main() {
int temp;
int sum = 0;
while (cin >> temp) {
sum += temp;
if (cin.get() == '\n') {
cout << sum << endl;
sum = 0;
}
}
return 0;
}
//输入有两行,第一行n
//第二行是n个空格隔开的字符串
//5
//c d a bb e
int main() {
int n;
cin >> n;
vector res;
string s;
for (int i = 0; i < n; i++) {
cin >> s;
res.push_back(s);
}
}
//多个测试用例,每个测试用例一行。
//每行通过空格隔开,有n个字符,n<100
//a c bb
//f dddd
//nowcoder
int main() {
string current;
vector array;
while (cin >> current) {
array.push_back(current);
if (cin.get() == '\n') {
sort(array.begin(), array.end());
for (string i : array)
cout << i << ' ';
cout << endl;
array.clear();
}
}
}
//多个测试用例,每个测试用例一行。
//每行通过, 隔开,有n个字符,n<100
//a, c, bb
//f, dddd
//nowcoder
int main() {
vector vs;
string a;
while (cin >> a)
{
int location = 0, index = 0;
while (location != -1)
{
location = a.find(",", index); if (location == -1) { vs.push_back(a.substr(index)); break; }
vs.push_back(a.substr(index, location - index));
index = location + 1;
}
sort(vs.begin(), vs.end());
for (int i = 0; i < vs.size() - 1; i++) {
cout << vs[i] << ",";
}
cout << vs[vs.size() - 1] << endl;
vs.clear();
}
system("pause");
}
//排序
//冒泡排序:冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列,一次比较两个元素,
//如果它们的顺序错误就把它们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
//这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。
class Solution {
public:
vector sortArray(vector& nums) {
int len = nums.size();
if (len == 0)
return nums;
for (int i = 0; inums[j + 1])
{
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
return nums;
}
};
//插入排序
//对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
class Solution {
public:
vector sortArray(vector& nums) {
int len = nums.size();
if (len <= 0)
return nums;
for (int i = 1; i= 0 && nums[preIndex]>current)
{
nums[preIndex + 1] = nums[preIndex];
preIndex--;
}
nums[preIndex + 1] = current;
}
return nums;
}
};
//
//从排序数组中删除重复项
class Solution {
public:
int removeDuplicates(vector& nums) {
if (nums.size() == 0)
{
return 0;
}
int i = 0;
for (int j = 1; j& prices) {
int max = 0;
int temp = 0;
for (int i = 1; i0)
{
max += temp;
}
}
return max;
}
};
//旋转数组 给定一个数组,将数组中的元素向右移动 k 个位置,其中 k 是非负数。
class Solution {
public:
void rotate(vector& nums, int k) {
int len = nums.size();
if (nums.empty() || ((k %= len) == 0))
{
return;
}
for (int i = 0; i& nums) {
int len = nums.size();
set s;
for (int i = 0; i length - 1)
return false;
}
for (int i = 0; i < length; ++i)
{
while (numbers[i] != i)
{
if (numbers[i] == numbers[numbers[i]])
{
*duplication = numbers[i];
return true;
}
// 交换numbers[i]和numbers[numbers[i]]
int temp = numbers[i];
numbers[i] = numbers[temp];
numbers[temp] = temp;
}
}
return false;
}
//不修改数组找出重复的数字(任意一个)
int getDuplication(const int* numbers, int length)
{
if (numbers == nullptr || length <= 0)
return -1;
int start = 1;
int end = length - 1;
while (end >= start)
{
int middle = ((end - start) >> 1) + start;
int count = countRange(numbers, length, start, middle);
if (end == start)
{
if (count > 1)
return start;
else
break;
}
if (count > (middle - start + 1))
end = middle;
else
start = middle + 1;
}
return -1;
}
int countRange(const int* numbers, int length, int start, int end)
{
if (numbers == nullptr)
return 0;
int count = 0;
for (int i = 0; i < length; i++)
if (numbers[i] >= start && numbers[i] <= end)
++count;
return count;
}
//只出现一次的数字 给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。
//相同数字的 ^ 为0
class Solution {
public:
int singleNumber(vector& nums) {
int len = nums.size();
int temp = 0;
for (int i = 0; i> arr)
{
int row = arr.size();
int col = arr[0].size();
if (!arr.empty() && row>0 && col>0)
{
int rows = 0;
int cols = col - 1;
while (rows0)
if (arr[rows][cols] == num)
{
cout << "find it" << endl;
return true;
}
else if (arr[rows][cols] intersect(vector& nums1, vector& nums2) {
int len1 = nums1.size();
int len2 = nums2.size();
vectorpi;
if (len1 == 0 || len2 == 0)
{
return pi;
}
sort(nums1.begin(), nums1.end());
sort(nums2.begin(), nums2.end());
int j = 0;
for (int i = 0; i= nums2[j])
{
if (nums1[i] == nums2[j])
{
pi.push_back(nums1[i]);
continue;
}
j++;
}
}
return pi;
}
};
//加一
class Solution {
public:
vector plusOne(vector& digits) {
int len = digits.size();
for (int i = 0; i& nums) {
int len = nums.size();
vector::iterator it;
int temp = 0;
for (it = nums.begin(); it != nums.end();)
{
if (*it == 0)
{
it = nums.erase(it);
temp += 1;
continue;
}
++it;
}
for (int j = 0; j twoSum(vector& nums, int target) {
vector result;
int len = nums.size();
for (int i = 0; i>& board) {
for (int i = 0; i<9; ++i)
{
if (isRowValid(i, board) == false)
return false;
}
for (int i = 0; i<9; ++i)
{
if (isColumnValid(i, board) == false)
return false;
}
for (int i = 0; i<9; i += 3)
{
for (int j = 0; j<9; j += 3)
{
if (isNineValid(i, j, board) == false)
return false;
}
}
return true;
}
bool isRowValid(int row, vector>& board)
{
vector temp;
for (int i = 0; i>& board)
{
vector temp;
for (int i = 0; i>& board)
{
vector temp;
for (int i = row; i>& matrix) {
int len = matrix[0].size();
for (int i = 0; i& s) {
char m;
int j = s.size() - 1;
for (int i = 0; i & s) {
int len = s.size();
reverse(s.begin(), s.end());
}
};
//整数反转 给出一个 32 位的有符号整数,你需要将这个整数中每位上的数字进行反转。
class Solution {
public:
int reverse(int x) {
long temp = 0;
while (x)
{
temp = temp * 10 + x % 10;
x /= 10;
if (temp > INT_MAX || temp m;
for (char c : s)
{
m[c]++;
}
for (int i = 0; i < s.size(); i++)
{
if (m[s[i]] == 1)
{
return i;
}
}
return -1;
}
};
//有效的字母异位词
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.size() != t.size())
return false;
sort(s.begin(), s.end());
sort(t.begin(), t.end());
for (int i = 0; i < s.size(); ++i)
{
if (s[i] != t[i])
return false;
}
return true;
}
};
//验证回文字符串
class Solution {
public:
bool isPalindrome(string s) {
vector temp1;
vector temp2;
for (int i = 0; i= 65 && s[i] <= 90) || (s[i] >= 97 && s[i] <= 122) || (s[i] >= 48 && s[i] <= 57))
{
s[i] = tolower(s[i]);
temp1.push_back(s[i]);
}
}
temp2 = temp1;
reverse(temp1.begin(), temp1.end());
if (temp1 == temp2)
return true;
else
return false;
}
};
//字符串转换整数(atoi)
class Solution {
public:
int myAtoi(string str) {
int temp = 0;
int i = 0;
while (str[i] == ' ')
i++;
if (str[i] == '-')
{
i++;
for (; i INT_MAX / 10 || (temp == INT_MAX / 10 && str[i] - '0' > 7))
{
return INT_MIN;
}
temp = 10 * temp + (int)(str[i] - '0');
}
else
break;
}
temp = -temp;
return temp;
}
else if (str[i] == '+')
{
i++;
for (; i INT_MAX / 10 || (temp == INT_MAX / 10 && str[i] - '0' > 7))
{
return INT_MAX;
}
temp = 10 * temp + (int)(str[i] - '0');
}
else
break;
}
return temp;
}
else if (isdigit(str[i]))
{
for (; i INT_MAX / 10 || (temp == INT_MAX / 10 && str[i] - '0' > 7))
{
return INT_MAX;
}
temp = 10 * temp + (int)(str[i] - '0');
}
else
break;
}
return temp;
}
else
return 0;
}
};
//实现strStr() 给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty())
return 0;
int len1 = haystack.size();
int len2 = needle.size();
for (int i = 0; i= len2)
{
string temp = haystack.substr(i, len2);
if (temp == needle)
return i;
else
continue;
}
}
return -1;
}
};
//报数 报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。
class Solution {
public:
string countAndSay(int n) {
if (n == 1)
return "1";
if (n == 2)
return "11";
string base = "11";
string result;
for (int i = 2; i& strs) {
string result = "";
if (strs.empty())
return result;
int len1 = strs.size();
int len2 = strs[0].size();
for (int i = 1; i length)
return;
int indexOfOriginal = originalLength;
int indexOfNew = newLength;
while (indexOfOriginal >= 0 && indexOfNew > indexOfOriginal)
{
if (str[indexOfOriginal] == ' ')
{
str[indexOfNew--] = '0';
str[indexOfNew--] = '2';
str[indexOfNew--] = '%';
}
else
{
str[indexOfNew--] = str[indexOfOriginal];
}
--indexOfOriginal;
}
}
//链表定义
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
//删除链表中的节点
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode* temp = node->next;
node->val = temp->val;
node->next = temp->next;
}
};
//删除链表的倒数第N个节点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *fast = head;
ListNode *slow = head;
while (n--)
{
if (fast == NULL)
return NULL;
fast = fast->next;
}
while (fast != NULL&&fast->next != NULL)
{
fast = fast->next;
slow = slow->next;
}
if (fast == NULL)
{
return head = head->next;
}
slow->next = slow->next->next;
return head;
}
};
//反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* now = head;
ListNode* fur = NULL;
ListNode* reverseNode = NULL;
while (now != NULL)
{
if (now->next == NULL)
{
reverseNode = now;
}
fur = now->next;
now->next = pre;
pre = now;
now = fur;
}
return reverseNode;
}
};
//合并两个有序链表
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL)
return l2;
if (l2 == NULL)
return l1;
ListNode* newHead = new ListNode(0);
ListNode* head = newHead;
while (l1 != NULL&&l2 != NULL)
{
if (l1->val >= l2->val)
{
head->next = l2;
l2 = l2->next;
}
else
{
head->next = l1;
l1 = l1->next;
}
head = head->next;
}
if (l1 == NULL)
head->next = l2;
if (l2 == NULL)
head->next = l1;
return newHead->next;
}
};
//回文链表
class Solution {
public:
bool isPalindrome(ListNode* head) {
if (head == NULL || head->next == NULL)
return true;
ListNode* fast = head;
ListNode* slow = head;
while (fast != NULL&&fast->next != NULL)
{
fast = fast->next->next;
slow = slow->next;
}
ListNode* pre = NULL;
ListNode* fur = NULL;
while (slow != NULL)
{
fur = slow->next;
slow->next = pre;
pre = slow;
slow = fur;
}
while (pre != NULL)
{
if (pre->val != head->val)
return false;
pre = pre->next;
head = head->next;
}
return true;
}
};
//环形链表
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL)
return false;
ListNode* slow = head;
ListNode* fast = head;
while (fast->next != NULL&&fast->next->next != NULL)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//二叉树的最大深度
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL)
return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
//二叉树的最小深度
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
return 0;
int left = minDepth(root->left);
int right = minDepth(root->right);
return (left == 0 || right == 0) ? left + right + 1 : min(left, right) + 1;
}
};
//前序遍历
void preorder(TreeNode *root, vector &path)
{
if (root != NULL)
{
path.push_back(root->val);
preorder(root->left, path);
preorder(root->right, path);
}
}
//中序遍历
void inorder(TreeNode *root, vector &path)
{
if (root != NULL)
{
inorder(root->left, path);
path.push_back(root->val);
inorder(root->right, path);
}
}
//后续遍历
void postorder(TreeNode *root, vector &path)
{
if (root != NULL)
{
postorder(root->left, path);
postorder(root->right, path);
path.push_back(root->val);
}
}
//验证二叉搜索树
class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValidBST(root, LONG_MIN, LONG_MAX);
}
bool isValidBST(TreeNode* root, long mn, long mx)
{
if (!root)
return true;
if (root->val <= mn || root->val >= mx)
return false;
return isValidBST(root->left, mn, root->val) && isValidBST(root->right, root->val, mx);
}
};
//对称二叉树 给定一个二叉树,检查它是否是镜像对称的
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL)
return true;
return isSymmetric(root->left, root->right);
}
bool isSymmetric(TreeNode* leftR, TreeNode* rightR)
{
if (leftR == NULL&&rightR == NULL)
return true;
if (leftR == NULL || rightR == NULL)
return false;
if (leftR->val != rightR->val)
return false;
return isSymmetric(leftR->left, rightR->right) && isSymmetric(leftR->right, rightR->left);
}
};
//二叉树的层次遍历
class Solution {
public:
vector> levelOrder(TreeNode* root) {
vector> result;
queuetemp;
if (root == NULL)
return result;
temp.push(root);
while (!temp.empty())
{
vectoreveryLayer;
queue next;
while (!temp.empty())
{
TreeNode* node = temp.front();
everyLayer.push_back(node->val);
temp.pop();
if (node->left != NULL)
{
next.push(node->left);
}
if (node->right != NULL)
{
next.push(node->right);
}
}
result.push_back(everyLayer);
temp = next;
}
return result;
}
};
class Solution {
public:
vector> levelOrder(TreeNode* root) {
vector> result;
pre(root, 0, result);
return result;
}
void pre(TreeNode* root, int depth, vector> &result)
{
if (!root)
return;
if (result.size() == depth)
result.push_back(vector{});
result[depth].push_back(root->val);
pre(root->left, depth + 1, result);
pre(root->right, depth + 1, result);
}
};
//将有序数组转换为二叉搜索树
class Solution {
public:
TreeNode* sortedArrayToBST(vector& nums) {
if (nums.size() == 0)
return NULL;
TreeNode* root = new TreeNode(nums[nums.size() / 2]);
vector temp1 = vector(nums.begin(), nums.begin() + nums.size() / 2);
vector temp2 = vector(nums.begin() + nums.size() / 2 + 1, nums.end());
root->left = sortedArrayToBST(temp1);
root->right = sortedArrayToBST(temp2);
return root;
}
};
//求二叉树第K层的节点个数
int get_k_level_number(TreeNode* root, int k) {
if (root == NULL || k <= 0) {
return 0;
}
if (root != NULL && k == 1) {
return 1;
}
return get_k_level_number(root->left, k - 1) + get_k_level_number(root->right, k - 1);
}
//合并两个有序数组
class Solution {
public:
void merge(vector& nums1, int m, vector& nums2, int n) {
int count = m + n - 1;
while (m>0 && n>0)
{
if (nums1[m - 1] >= nums2[n - 1])
{
nums1[count] = nums1[m - 1];
m--;
}
else
{
nums1[count] = nums2[n - 1];
n--;
}
count--;
}
while (n>0)
{
nums1[count] = nums2[n - 1];
count--;
n--;
}
return;
}
};
//第一个错误的版本
bool isBadVersion(int version);
class Solution {
public:
int firstBadVersion(int n) {
int start = 1;
int end = n;
while (start <= end)
{
int mid = start + (end - start) / 2;
if (!isBadVersion(mid))
{
start = mid + 1;
}
else
end = mid - 1;
}
return start;
}
};
//爬楼梯
class Solution {
public:
int climbStairs(int n) {
if (n == 1)
return 1;
int* step = new int[n + 1];
step[1] = 1;
step[2] = 2;
for (int i = 3; i <= n; i++)
{
step[i] = step[i - 1] + step[i - 2];
}
return step[n];
}
};
//买卖股票的最佳时机
class Solution {
public:
int maxProfit(vector& prices) {
if (prices.size() == 0)
return 0;
int min = prices[0];
int temp = 0;
int result = 0;
for (int i = 0; i& nums) {
if (nums.size() == 0)
return 0;
if (nums.size() == 1)
return nums[0];
int* step = new int[nums.size()];
step[0] = nums[0];
int result = step[0];
for (int i = 1; i0)
step[i] = step[i - 1] + nums[i];
else
step[i] = nums[i];
result = max(step[i], result);
}
return result;
}
};
//打家劫舍
class Solution {
public:
int rob(vector& nums) {
if (nums.size() == 0)
return 0;
if (nums.size() == 1)
return nums[0];
int* step = new int[nums.size() + 1];
step[0] = 0;
step[1] = nums[0];
int result = nums[0];
for (int i = 2; i <= nums.size(); i++)
{
if (step[i - 1]>nums[i - 1] + step[i - 2])
step[i] = step[i - 1];
else
step[i] = nums[i - 1] + step[i - 2];
}
return step[nums.size()];
}
};
//打乱一个没有重复元素的数组。
class Solution {
public:
Solution(vector& nums) {
orinums = nums;
shuffnums = nums;
}
/** Resets the array to its original configuration and return it. */
vector reset() {
return orinums;
}
/** Returns a random shuffling of the array. */
vector shuffle() {
for (int i = 0; i orinums;
vector shuffnums;
};
//最小栈
class MinStack {
public:
/** initialize your data structure here. */
MinStack() {
}
void push(int x) {
if (s2.empty() || s2.top() >= x)
s2.push(x);
s1.push(x);
}
void pop() {
if (s1.top() == s2.top())
s2.pop();
s1.pop();
}
int top() {
return s1.top();
}
int getMin() {
return s2.top();
}
private:
stack s1;
stack s2;
};
//Fizz Buzz
class Solution {
public:
vector fizzBuzz(int n) {
vector result;
for (int i = 1; i <= n; i++)
{
if (i % 3 == 0 && i % 5 == 0)
result.push_back("FizzBuzz");
else if (i % 3 == 0)
result.push_back("Fizz");
else if (i % 5 == 0)
result.push_back("Buzz");
else
result.push_back(to_string(i));
}
return result;
}
};
//计数质数
class Solution {
public:
int countPrimes(int n) {
vector temp(n, 1);
int count = 0;
for (int i = 2; i0)
{
if (n & 1 == 1)
count++;
n = n >> 1;
}
return count;
}
};
class Solution {
public:
int hammingWeight(uint32_t n) {
int count = 0;
while (n>0)
{
n = n&(n - 1);
count++;
}
return count;
}
};
//汉明距离
class Solution {
public:
int hammingDistance(int x, int y) {
int result = 0;
result = x^y;
int count = 0;
while (result>0)
{
result = result&(result - 1);
count++;
}
return count;
}
};
//颠倒二进制位
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int res = 0;
for (int i = 0; i<32; ++i)
{
res <<= 1;
res = res + (n & 1);
n >>= 1;
}
return res;
}
};
//帕斯卡三角形
class Solution {
public:
vector> generate(int numRows) {
vector> res;
vector everylayer;
if (numRows == 0)
return res;
everylayer.push_back(1);
res.push_back(everylayer);
if (numRows == 1)
return res;
if (numRows>1)
{
for (int i = 2; i <= numRows; i++)
{
everylayer.clear();
everylayer.push_back(1);
for (int j = 0; j temp;
temp.push(0);
for (int i = 0; i& nums) {
sort(nums.begin(), nums.end());
for (int i = 0; i