leetcode Day15----array.easy

K-diff Pairs in an Array

Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k.

Example 1:
Input: [3, 1, 4, 1, 5], k = 2
Output: 2
Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).
Although we have two 1s in the input, we should only return the number of unique pairs.
Example 2:
Input:[1, 2, 3, 4, 5], k = 1
Output: 4
Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5).
Example 3:
Input: [1, 3, 1, 5, 4], k = 0
Output: 1
Explanation: There is one 0-diff pair in the array, (1, 1).
Note:
The pairs (i, j) and (j, i) count as the same pair.
The length of the array won’t exceed 10,000.
All the integers in the given input belong to the range: [-1e7, 1e7].

偏难的一道题 通过率只有29.6% 难点在于如何降低时间复杂度,很容易就超时了

好吧,,真滴有点难。。我做不出来,下面放的是其他大佬写的代码。
在这里插入图片描述

C语言

#define SIZE 1000
struct HashArray
{
    int key;
    int count;
    struct HashArray* next;
}Hash[SIZE];       //主函数中需要初始化
void addHash(int num)     //在Hash table中添加数据
{
    int temp=abs(num%SIZE);     //添加的数据可包括负数
    if(Hash[temp].key==0)
    {
        Hash[temp].key=num;
        Hash[temp].count++;
    }else if(Hash[temp].key==num)
    {
        Hash[temp].count++;     
    }else
    {
        struct HashArray *p=&Hash[temp]; 
        while(p->key!=num&&p->next!=NULL)    
        {p=p->next;}
        if(p->key==num)
        {p->count++;}
        else
        {
            p->next=(struct HashArray*)malloc(sizeof(struct HashArray));
            p=p->next;
            p->key=num;
            p->count=1;
            p->next=NULL;
        }
    }   
}
int findHash(int nums_temp,int k){
    int num=nums_temp;
    int temp=abs(num%SIZE);     //添加的数据可包括负数
    if(k==0){
        if(Hash[temp].key==num)
        {
            if(Hash[temp].count==-1){return 0;}
            if(Hash[temp].count>1){
                Hash[temp].count=-1; 
                return 1;
            }
            Hash[temp].count=-1; 
        }else
        {
            struct HashArray *p=&Hash[temp]; 
            while(p->key!=num&&p->next!=NULL)    
            {p=p->next;}
            if(p->key==num)
            {
                if(p->count==-1){return 0;}
                if(p->count>1){
                    p->count=-1; 
                    return 1;
                }
                p->count=-1;  
            }
        }
        return 0;
    }
    if(Hash[temp].key==num)
    {
        if(Hash[temp].count==-1){return 0;}
        Hash[temp].count=-1; 
    }else
    {
        struct HashArray *p=&Hash[temp]; 
        while(p->key!=num&&p->next!=NULL)    
        {p=p->next;}
        if(p->key==num)
        {
            if(p->count==-1){return 0;}
            p->count=-1; 
        }
    }  
    num=nums_temp+k;
    temp=abs(num%SIZE);     //添加的数据可包括负数
    if(Hash[temp].key==0&&Hash[temp].count==0)
    {
       return 0;
    }else if(Hash[temp].key==num&&Hash[temp].count!=0)
    {
        return 1;     
    }else
    {
        struct HashArray *p=&Hash[temp]; 
        while(p->key!=num&&p->next!=NULL)    
        {p=p->next;}
        if(p->key==num&&p->count!=0)
        {return 1;}
    }
    return 0;
}

int findPairs(int* nums, int numsSize, int k) {
    if(k<0){return 0;}
    int ret=0;
    for(int i=0;i<SIZE;i++){
        Hash[i].key=0;
        Hash[i].count=0;
        Hash[i].next=NULL;
    }
    for(int i=0;i<numsSize;i++){
        addHash(nums[i]);
    }
    for(int i=0;i<numsSize;i++){
        if(findHash(nums[i],k)){
            ret++;
        }
    }
    return ret;
}

Success
Details
Runtime: 12 ms, faster than 97.33% of C online submissions for K-diff Pairs in an Array.
Memory Usage: 8.6 MB, less than 20.00% of C online submissions for K-diff Pairs in an Array.

python3

class Solution:
    def findPairs(self, nums: List[int], k: int) -> int:
        if k < 0:
            return 0
        elif k == 0:
            return len(set([i for i in nums if nums.count(i)>1]))
        else:
            nums = list(set(nums))
            x = [i-k for i in nums] + nums
            return len(x)-len(set(x))

Success
Details
Runtime: 60 ms, faster than 48.99% of Python3 online submissions for K-diff Pairs in an Array.
Memory Usage: 14.8 MB, less than 12.09% of Python3 online submissions for K-diff Pairs in an Array.

Array Partition I

Given an array of 2n integers, your task is to group these integers into n pairs of integer, say (a1, b1), (a2, b2), …, (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible.

Example 1:
Input: [1,4,3,2]

Output: 4
Explanation: n is 2, and the maximum sum of pairs is 4 = min(1, 2) + min(3, 4).
Note:
n is a positive integer, which is in the range of [1, 10000].
All the integers in the array will be in the range of [-10000, 10000].

哈哈这道题就简单许多啦,先排序,再每隔一个数加总。加下标为0,2,4…的数即可。
其中C语言中用到的是快速排序,平均时间复杂度是O(nlogn)

C语言

void swap(int *a, int *b){
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}
void quicksort(int array[], int maxlen, int begin, int end){
    int i, j;
    if(begin<end){
        i=begin + 1;
        j=end;
        while(i<j){  
            if(array[i]>array[begin]){
                swap(&array[i], &array[j]);
                j--;
            }
            else{i++;}
        }
        if(array[i] >= array[begin]){
            i--;  
        }  
  
        swap(&array[begin], &array[i]);          
        quicksort(array, maxlen, begin, i);  
        quicksort(array, maxlen, j, end);  
    }  
}  

int arrayPairSum(int* nums, int numsSize){
    quicksort(nums,numsSize,0,numsSize-1);
    int i=0,sum=0;
    while(i<numsSize){
        sum+=nums[i];
        i+=2;
    }
    return sum;
}

Success
Details
Runtime: 40 ms, faster than 64.33% of C online submissions for Array Partition I.
Memory Usage: 8.4 MB, less than 100.00% of C online submissions for Array Partition I.

python3

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        sum=0
        i=0
        while(i<len(nums)):
            sum+=nums[i]
            i+=2
        return sum
        

Success
Details
Runtime: 120 ms, faster than 21.40% of Python3 online submissions for Array Partition I.
Memory Usage: 15 MB, less than 5.20% of Python3 online submissions for Array Partition I.

Reshape the Matrix

In MATLAB, there is a very useful function called ‘reshape’, which can reshape a matrix into a new one with different size but keep its original data.

You’re given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to be filled with all the elements of the original matrix in the same row-traversing order as they were.

If the ‘reshape’ operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.

Example 1:
Input:
nums =
[[1,2],
[3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
[3,4]]
r = 2, c = 4
Output:
[[1,2],
[3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.

C语言

做不出来。。。。

python3

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        if nums is None:
            return None
        
        if r*c != len(nums) * len(nums[0]):
            return nums
             
        re = []
        tem = []
        for row in range(len(nums)):
            for col in range(len(nums[0])):
                tem.append(nums[row][col])
                
        for ind in range(0, r*c, c):
            re.append(tem[ind:ind+c])
        
        return re

Success
Details
Runtime: 92 ms, faster than 71.66% of Python3 online submissions for Reshape the Matrix.
Memory Usage: 14.3 MB, less than 5.66% of Python3 online submissions for Reshape the Matrix.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值