How to improve my c++ code's runtime efficency [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I'm doing a leetcode problem 986. Interval List Intersections, I don't know why my O(m+n) solution, even the official solution only beats 5% submissions on runtime. How other people make it runs faster? Is there any ways or suggestions to improve my code? Thanks a lot.
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res;
int i = 0, j = 0;
while(i < A.size() && j < B.size()) {
int lo = max(A[i][0], B[j][0]);
int hi = min(A[i][1], B[j][1]);
if(lo <= hi) {
vector<int> temp{lo, hi};
res.push_back(temp);
}
if(A[i][1] <= B[j][1])
++i;
else
++j;
}
return res;
}
};

Ok, I've done it for you. See my comments in the code.
class Solution {
public:
vector<vector<int>> intervalIntersection(vector<vector<int>>& A, vector<vector<int>>& B) {
vector<vector<int>> res;
// Avoid reallocations, reserve enough memory.
res.reserve(A.size() + B.size());
int i = 0, j = 0;
// Hint to the compiler: A.size() and B.size() are immutable.
const int ii = A.size(), jj = B.size();
while(i < ii && j < jj) {
const int lo = max(A[i][0], B[j][0]);
const int hi = min(A[i][1], B[j][1]);
if(lo <= hi) {
// Construct inner vector in-place.
res.push_back(std::vector<int>({lo, hi}));
}
if(A[i][1] <= B[j][1])
++i;
else
++j;
}
return res;
}
};
The result:
Runtime: 56 ms, faster than 46.23% of C++ online submissions for Interval List Intersections.
Memory Usage: 13 MB, less than 100.00% of C++ online submissions for Interval List Intersections.
Accepted 56 ms 13 MB cpp

Related

Determine if all values in a vector occur equally often [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 10 days ago.
This post was edited and submitted for review 10 days ago.
Improve this question
What is wrong with this code?
class Solution {
public:
bool uniqueOccurrences(vector<int> &arr) {
map<int, int> mp;
for (auto x : arr) {
mp[x]++;
}
vector<int> v;
for (auto x : mp) {
v.push_back(x.second);
}
sort(v.begin(), v.end());
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] != v[i + 1])
return true;
}
return false;
}
};
Given an array of integers arr, return true if the number of occurrences of each value in the array is unique or false otherwise.
This was the question statement and was working fine with various test cases but fails in the follow test case: [3,5,-2,-3,-6,-6] should return false but returns true
Your problem is here:
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] != v[i + 1])
return true;
}
return false;
You should swap the return true and return false.
for (int i = 0; i < v.size() - 1; i++) {
if (v[i] != v[i + 1])
return false;
}
return true;

Why does leetcode accept code which wouldnt usually be ran in an IDE? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last month.
Improve this question
Okay so the following class was accepted and ran in the Two sum problem in leetcode:
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> arr(2);
for(int i = 0; i < nums.size(); i++){
for(int j = i+1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
arr[0] = i;
arr[1] = j;
}
}
}
return arr;
}
};
I then tried to use this within my IDE (codeblocks), but i have to make the vector nums constant... why do i have to do this in codeblocks but leetcode somehow ignores this?
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> twoSum(const vector<int>& nums, int target) {
vector<int> arr(2);
for(int i = 0; i < nums.size(); i++){
for(int j = i+1; j < nums.size(); j++){
if(nums[i] + nums[j] == target){
arr[0] = i;
arr[1] = j;
}
}
}
return arr;
}
};
int main() {
Solution solution;
solution.twoSum({2,7,11,15},9);
}
Second question ( i know... greedy )
Why, when i run my code (in codeblocks) i get nothing returned?
Codeblocks
But, when i run it in leetcode, i get the expected results?
Leetcode
Well, if the signature of twoSum has a vector<int>& parameter, you're not allowed to call twoSum with {2,7,11,15} as an argument, because that would require the creation of a temporary vector, and vector<int>& is not allowed to bind to that temporary. You would need to add const to the referenced type. This will be the case regardless of whether the code is being compiled on LeetCode or in your local environment.
The thing about LeetCode is that you can't actually see the code that's used to call twoSum. Perhaps that code looks more like the following:
vector<int> nums;
// load input values into `nums`
vector<int> result = solution.twoSum(nums, target);
In this case, there is no temporary, and the reference can bind to nums without any issues.

SelectionSorting in c++ (Error : EXC_BAD_ACCESS) [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I just recently learned to do selection sorting an array. I am also using X-Code on a mac.
I thought I did everything correctly, but I seem to keep getting this error message on the if statement :
Thread 1: EXC_BAD_ACCESS(code=1, address=0x7fff5fc00000).
What am I doing wrong?
using namespace std;
void selectionSorting(int array[], int n)
{
for(int i = 0; i < n-1; n++)
{
int min = i;
for(int j = i + 1; j < n; j++)
{
if(array[j] < array[min]) //Thread 1: EXC_BAD_ACCESS(code=1, address=0x7fff5fc00000)
min = j;
}
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
int main()
{
int n = 10;
int array[]= {10,9,8,7,6,5,4,3,2,1};
selectionSorting(array, n);
for(int x=0; x < n; x++)
{
cout << array[x] << " ";
}
return 0;
}
You have a logical error at for(int i = 0; i < n-1; n++). It should be for(int i = 0; i < n-1; i++) (iterate through the elements of the array).
Also EXC_BAD_ACCESS suggests that your are trying to access a piece of memory that is no longer accessible or it doesn't go well with the intended use.
See that this occurs at if(array[j] < array[min]), which is obvious because j is going beyond the array length as you do n++.
As suggested in the comments try using a debugger.

Finding closest numbers within two arrays [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I have to find closest numbers within two arrays and shows their difference. I am using a loop for that but it takes too much time. Do you know any way to make that algorithm faster?
#include <cmath>
#include <cstdio>
using namespace std;
long long int red, yellow, minimum = 1000000000, difference = 0;
long long int TC[100001], ZT[100001];
int main()
{
scanf("%d", &red);
for (int y = 0; y < red; ++y)
{
scanf("%d", &TC[y]);
}
scanf("%d", &yellow);
for (int yy = 0; yy < yellow; ++yy)
{
scanf("%d", &ZT[yy]);
}
for (int yyy = 0; yyy < red; ++yyy)
{
for (int i = 0; i < yellow; ++i)
{
difference = abs(TC[yyy] - ZT[i]);
if (difference == 0)
{
minimum = 0;
break;
}
else if (difference < minimum)
minimum = difference;
}
}
printf("%d \n", minimum);
}
This shoud be O(nlgn):
sort two lists
let i = 0, j = 0, minval = abs(list1[0] - list2[0])
as long as both lists have more items:
minval = min(minval, abs(list1[i] - list2[j])
if abs(list1[i + 1] - list2[j]) < abs(list1[i] - list2[j + 1])
increment i
else increment j
If you sort them, you can optimize algorithm to run much faster. When your both arrays are sorted, you can check one by one and compare them less than your current algorithm. Because you'll skip some of them, since you know they are sorted.
By the way, since you get the numbers from user, I suggest you to put numbers in sorted. Every time user enters a number, put the number in a place where numbers after it are bigger than it and numbers before it are less than it. To do such a thing, maybe using linked list is better idea (or easier).

Quicksort didn't do anything, now stuck in forever loop [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I'm trying to implement the in-place version of quicksort. This is my code:
#include <vector>
#include <algorithm>
using namespace std;
size_t partition(vector<int>& v, size_t l, size_t r, size_t p)
{
size_t pivot = v[p];
swap(v[p], v[r]);
size_t store = l;
for (size_t i = l; l < (r-1); i++) {
if (v[i] <= pivot) {
swap(v[i], v[store]);
store++;
}
}
swap(v[store], v[r]);
return store;
}
void quickSort(vector<int>& v, size_t l, size_t r)
{
//If two or more elements
if(l<r)
{
size_t pI = l;
size_t nP = partition(v, l, r, pI);
quickSort(v, (nP+1), r);
quickSort(v, l, (nP-1));
}
}
For reference, I'm using the pseudocode for the in-place version on wikipedia.
The problems I'm having is that I at first accidentily called the function with the middle of the list as the leftmost arguemtn. the program ran error free and ouputted the new list, totally unchanged and unsorted (no errors at all). I found my error, and now I call the function like this:
quickSort(v, 0, (v.size()-1));
And Xcode warns me that I'm getting stuck in a forever loop at
if (v[i] <= pivot)
It's at that exact line, as if the comparison triggers something. I would be delighted if you could help me!
Your problem is that you're comparing l < r - 1 but incrementing i on every iteration of the for loop. Hence, infinite loop. Change for (size_t i = l; l < (r-1); i++) { to for (size_t i = l; i < (r-1); i++) {.