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