算法设计与结构基础作业第六周

本文介绍了两种常见的算法实现:字符串的反转及数组中重复元素的查找。通过C++代码展示了如何有效地完成这两种操作,同时探讨了算法的时间复杂度。

344.Reverse String

Decription:

Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".

My C++ code:

class Solution {
public:
    string reverseString(string s) {
        int i = 0 ;
        int j = s.size() - 1 ;
        while (i < j)
        {
            swap(s[i] , s[j]) ;
            i ++ ;
            j -- ;
        }
        return s ;
    }
};

442.Find All Duplicates in an Array

Description:

Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements that appear twice in this array.

Could you do it without extra space and in O(n) runtime?

Example:

Input:
[4,3,2,7,8,2,3,1]

Output:
[2,3]

分析:
      题目很简单,找出一个数组中重复出现了两次的数字。注意时间O(n)。

My C++ Code:

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        int length = nums.size() ;
        sort(&nums[0] , &nums[length - 1]) ;
        vector<int> res ;
        int temp = 0 ;
        for(int i = 0 ; i < length - 1 ; i ++)
        {
            if(nums[i] == nums[i + 1])
                res.push_back(1) ;
                res[temp] == nums[i] ;
                temp ++ ;
        }
        return res ;
    }
};

!!!!!:
      这个题目我并没有完全做出来,我的想法是排序之后,比较相邻的两个数字,如果相等就是重复的数字(因为一个数字最多出现两次)。但是一直超时。老师如果看到后希望可以解答。谢谢老师!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值