classSolution { public: voidreverse(vector<int>& nums, int start, int end){ while (start < end) { swap(nums[start], nums[end]); start += 1; end -= 1; } } voidrotate(vector<int>& nums, int k){ k %= nums.size(); reverse(nums, 0, nums.size() - 1); reverse(nums, 0, k - 1); reverse(nums, k, nums.size() - 1); } };
未整理
公共前缀
classSolution { public: string longestCommonPrefix(vector<string>& strs) { if (!strs.size()) { return""; } string prefix = strs[0]; int count = strs.size(); for (int i = 1; i < count; ++i) { prefix = longestCommonPrefix(prefix, strs[i]); if (!prefix.size()) { break; } } return prefix; } string longestCommonPrefix(const string& str1, const string& str2) { int length = min(str1.size(), str2.size()); int index = 0; while (index < length && str1[index] == str2[index]) { ++index; } return str1.substr(0, index); } };
合并两个正序数组
classSolution { public: voidmerge(vector<int> &nums1, int m, vector<int> &nums2, int n){ int i = nums1.size() - 1; m--; n--; while (n >= 0) { while (m >= 0 && nums1[m] > nums2[n]) { swap(nums1[i--], nums1[m--]); } swap(nums1[i--], nums2[n--]); } } };
回文数
#include<cmath> #include<iostream> usingnamespace std; classSolution { public: int index = 0; int first = 0, last = 0; int t = 0; boolisPalindrome(int x) { if (x < 0) { returnfalse; }
t = x; while (x != 0) { x = x / 10; index++; }
for (int i = 1; i < index / 2 + 1; i++) { first = getNumOfPosition(t, i, index); last = getNumOfPosition(t, index + 1 - i, index); if (first != last) { returnfalse; } } returntrue; } intgetNumOfPosition(int x, int pos, int index) { x = x / pow(10, pos - 1); x = x % 10; return x; } };
classSolution { public: intclimbStairs(int x){ int a = 1, b = 2, s = 0; if (x <= 2) { return x; } else { for (int ret = 3; ret <= x; ret++) { s = a + b; a = b; b = s; } } return s; } };