3.18~InsertionSort And Pairs

转载注明出处  http://www.cnblogs.com/ligun123/archive/2013/03/19/2969438.html

先是跟着Hackerrank练习了下插入排序

然后又做了Pairs,来源:https://www.hackerrank.com/challenges/pairs

Given N numbers [N<=10^5], count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]. Each of the N numbers will be > 0 and be less than K away from 2^31-1 (Everything can be done with 32 bit integers).

Input Format:

1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.

Output Format:

One integer saying the no of pairs of numbers that have a diff K.

Sample Input #00:

5 2
1 5 3 4 2

Sample Output #00:

3

Sample Input #01:

10 1
363374326 364147530 61825163 1073065718 1281246024 1399469912 428047635 491595254 879792181 1069262793 

Sample Output #01:

0

 

一开始没读懂啥题,多了几遍才晓得,是计算有多少对这样的数,他们相差为K?

可以先将原来的数组从小到大排序,然后查找其中每一个值(arr[i] + K)是否在这个数组中,是的话pairs +1,最后打印pairs

//
//  main.c
//  InsertionSort  &  Pairs
//
//  Created by Kira on 3/18/13.
//  Copyright (c) 2013 Kira. All rights reserved.
//

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <assert.h>

/* Head ends here */
void insertionSort(unsigned long int ar_size, unsigned long int * ar) {
    if (ar_size > 1) {
        insertionSort(ar_size-1, ar);
    }
    if (ar_size == 1) {
        return;
    }
    unsigned long int key = ar[ar_size-1];
    for (long long int i = ar_size -2; i >= 0; i --) {
        if (key < ar[i]) {
            ar[i +1] = ar[i];
        } else {
            ar[i +1] = key;
            break;
        }
        if (i ==0) {
            ar[i] = key;
        }
    }
}

int compare(const void *d1, const void *d2)
{
    return *(int*)(d1) - *(int*)(d2);
}

/* Tail starts here */
int main() {
    
    unsigned long int N = 0, K = 0, *array = NULL;
    scanf("%ld", &N);
    scanf("%ld", &K);
    array = calloc(N, sizeof(unsigned long));
    unsigned long int i = 0;
    while (i < N) {
        scanf("%ld", &array[i]);
//        insertionSort(i +1, array);  //最开始用自己之前写的插入排序,结果时间复杂度不过关,然后替换成了系统的qsort
        i ++;
    }
    
    qsort(array, N, sizeof(unsigned long), compare);
    
    unsigned long int count = 0;
    for (int ii = 0; ii < N; ii ++) {
        unsigned long int key = array[ii] + K;
        unsigned long begin = ii +1;
        unsigned long end = N-1;
        while (begin <= end) {
            unsigned long int mid = (begin + end) /2;
            if (array[mid] < key) {
                begin = mid+1;
            }
            else if (array[mid] > key) {
                end = mid-1;
            }
            else if (array[mid] == key) {
                count ++;
                break;
            }
        }
    }
    
    free(array);
    array = NULL;
    
    printf("%ld", count);
    return 0;
}

 

posted @ 2013-03-19 16:21  痴人指路  阅读(335)  评论(0编辑  收藏  举报