Home > Article > Backend Development > Common pitfalls and optimization strategies of C++ time complexity
It is crucial to understand the time complexity trap. Optimization strategies include: 1. Use the correct algorithm; 2. Reduce unnecessary copies; 3. Optimize traversal. Practical examples explore optimization methods for calculating the sum of squares of an array, converting a string to uppercase, and finding elements in an unordered array.
C Common pitfalls of time complexity and optimization strategies
Common pitfalls of time complexity:
Optimization strategy:
Practical case:
Trap: The purpose of the following code is to calculate the sum of squares of each element in the array.
int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } int sum = 0; for (int i = 0; i < n; i++) { sum += pow(arr[i], 2); } cout << sum << endl; return 0; }
Problem: The code that appears to only loop once actually loops through each element in the array twice: once for the input and once for calculating the sum of squares.
Optimization: Optimize this code by simultaneously calculating the sum of squares in the input stage.
int main() { int n; cin >> n; int arr[n]; int sum = 0; for (int i = 0; i < n; i++) { cin >> arr[i]; sum += pow(arr[i], 2); } cout << sum << endl; return 0; }
Trap: The following code converts a string to uppercase.
string toUpperCase(string s) { int n = s.length(); for (int i = 0; i < n; i++) { s[i] = toupper(s[i]); } return s; }
Problem: This code copies the string on each iteration.
Optimization: Use reference parameters to avoid unnecessary copies.
void toUpperCase(string& s) { int n = s.length(); for (int i = 0; i < n; i++) { s[i] = toupper(s[i]); } }
Trap: The following code searches for elements in an unordered array.
int findElement(int arr[], int n, int x) { for (int i = 0; i < n; i++) { if (arr[i] == x) { return i; } } return -1; }
Problem: The time complexity of traversing an unordered array is O(n).
Optimization: Optimize this code by sorting the array, thus reducing the time complexity to O(log n).
int findElement(int arr[], int n, int x) { sort(arr, arr + n); // O(n log n) int l = 0, r = n - 1; while (l <= r) { int mid = (l + r) / 2; if (arr[mid] == x) { return mid; } else if (arr[mid] < x) { l = mid + 1; } else { r = mid - 1; } } return -1; }
The above is the detailed content of Common pitfalls and optimization strategies of C++ time complexity. For more information, please follow other related articles on the PHP Chinese website!