optimized this code

Pages: 12
[ Edit: in the code below, A[i] should A[A[i]] (two places). See tpb's comment below. ]

For the original problem, something like:
1
2
3
4
5
6
7
8
9
10
11
bool findIt(const vector<int> &A) {
    vector<int> values(A.size()+1);
    for (int i=1; i<A.size(); ++i) {  // deliberately start at index 1.
        if (values.find(A[i]) != values.end()) {
            return true;
        } else {
            values.insert(A[i]);
        }
    }
    return false;
}
Last edited on
Optimize it please

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int happiness(int *arr, int N) {
    int flag = 0;
    for (int i = 0; i < N; i++) {
        for (int j = 0; j < N; j++) {
            if (i != j) {
                if (arr[i] != arr[j]) {
                    if (arr[arr[i] - 1] == arr[arr[j] - 1]) {
                        flag = 1;
                        break;
                    }
                }
            }
        }
        if (flag == 1) {
            break;
        }
    }
    if (flag == 1) {
        return 1;
    } else {
        return 0;
    }
}
Optimize it please
Read my previous post.
@dhayden, Are you solving the problem, though? You never even test A[A[...]], only A[...]. I understand the problem to be is there an i, j such that A[i] != A[j] yet A[A[i]] == A[A[j]]
tpb, I'm not solving the problem, that post was off the top of my head. You're right, A[i] should be A[A[i]]. Thanks for pointing out the error. I'll edit my post.
Topic archived. No new replies allowed.
Pages: 12