LeetCode 219:Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the difference between i and jis at most k.

给定一个数组和一个整数k,找出输足内是否存在两个元素nums[i]和nums[j]相等,并且j - i 小于等于 k。


就是一个窗口在数组内滑动。。。不过有三点需要注意,一是k小于等于0时直接返回false;二是相邻整数k代表的窗口大小是k+1(我之前一直以为是k-1,然后死活做不对);三是因为题目没有规定不能改变原数组,所以在k大于等于nums.size()+1时,可以直接对原数组进行排序,然后判断相邻元素是否相等,这样可以节省大量时间。

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        if(k<=0) return false;
        if(nums.size()==0||nums.size()==1) return false;
        if(k>=nums.size()-1)
        {
            sort(nums.begin(),nums.end());
            for(int i=0;i<nums.size()-1;i++)
                if(nums[i]==nums[i+1]) return true;
            return false;
        }
        vector<int> temp;
        int i,j;
        for(i=0;i<=k;i++)
            temp.push_back(nums[i]);
        vector<int> temp1=temp;
        sort(temp1.begin(),temp1.end());
        for(int i=0;i<temp1.size()-1;i++)
            if(temp1[i]==temp[i+1]) return true;
        for(i=k+1;i<nums.size();i++)
        {
            temp.push_back(nums[i]);
            temp.erase(temp.begin());
            for(j=0;j<temp.size()-1;j++)
                if(temp[j]==temp[temp.size()-1]) return true;
            
        }
        temp.push_back(nums[i]);
        temp.erase(temp.begin());
        for(j=0;j<temp.size()-1;j++)
        if(temp[j]==temp[temp.size()-1]) return true;
        return false;
    }
};
还是写得很丑。。。哎感觉最近都没灵性了,要么复制粘贴代码,要么强行开辟个数组浪费空间。。。真是,哎



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值