Last active
June 4, 2020 09:38
-
-
Save bhaveshmunot1/6310854c88807d4a811e0a00cafc75cc to your computer and use it in GitHub Desktop.
Examples to Understand Time Complexity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int sum(vector<int> nums) { | |
int ans = 0; // 1 | |
for (int i=0; i<nums.size(); i++) { // n times | |
ans += nums[i]; // 1 | |
} | |
return ans; // 1 | |
} | |
void efficient(vector<int> nums) { | |
int addition = sum(nums); // O(n). Note: Single line does not | |
// mean constant time. | |
for (int i=0; i<n; i++) { // n times | |
nums[i] = nums[i] + addition; // 1 | |
} | |
} | |
void inefficient(vector<int> nums) { | |
for (int i=0; i<n; i++) { // n times | |
nums[i] = nums[i] + sum(nums); // O(n) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment