从今天开始,辣鸡刘学习一下搞搞算法,确定了leetcode网站,从最简单的开始学习和思考。
入门算法,
1. Two Sum
描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
举例:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
简单翻译:
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
虽然很简单,但是已经好久没写过Java的辣鸡刘也写了十几分钟,而且复杂度相当高,不推荐大家用,别问我为啥没用Python,因为昨晚没写出来(逃
class Solution {
public int[] twoSum(int[] nums, int target) {
首先获取数组长度
int len=nums.length;
两个循环进行遍历
for (int i=0;i < len;i++)
{
for (int j=i+1;j < len;j++)
因为同样的元素不能重复使用,所以j从1开始
{
if (target == nums[i]+nums[j])
{
return new int[] {i, j};
}
}
}
我试过了,这句话得加着
throw new IllegalArgumentException("No such nunbers");
}
}
复杂度分析:
时间复杂度:O(n^2), 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间。因此时间复杂度为 O(n^2)。
空间复杂度:O(1)。
另外这是我的Python版本,不知道为啥一直报错,有算法好的兄弟可以指导一二,谢谢了
class Solution:
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
l=len(nums);
for i,j in l:
if (target=nums[i]+nums[j]) and (i!=j) :
return [i,j]
2. 整数反转
题目描述:
Given a 32-bit signed integer, reverse digits of an integer.
给定一个 32 位有符号整数,将整数中的数字进行反转。
实例:
输入: 123
输出: 321
输入: -123
输出: -321
输入: 120
输出: 21
冗长而又原始的代码来了,这次我用Python做的,起初想用一些函数,但是为了更原始一些,所以尽量避免函数的选用:
思路很简单:将输入的整数转为字符串,反向遍历,再组合成整数;其中按照正负数分了两个判断:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
res_list = [];
list2=[];
str1=str(x);
str_list=list(str1);
l=len(str_list);
if str_list[0] is '-':
print('负数');
for i in str_list[::-1]:
res_list.append(i);
res = "".join(res_list);
res_list.remove('-')
res_list.insert(0, '-');
res = "".join(res_list);
print(res);
else:
print('正常情况');
for i in str_list[::-1]:
res_list.append(i);
print("".join(res_list));
res = "".join(res_list);
if abs(int(res))>2147483647:
print('越界')
return 0
else:
print('最终返回:',res)
return int(res);
当然如果用函数的话,简单:
class Solution:
def reverse(self, x):
"""
:type x: int
:rtype: int
"""
s = int(str(abs(x))[::-1])
if s > 2147483647 or s < -2147483648 :
return 0
return s if x > 0 else -s
3. 回文数
描述:
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
示例 1:
输入: 121
输出: true
示例 2:
输入: -121
输出: false
解释: 从左向右读, 为 -121 。 从右向左读, 为 121- 。因此它不是一个回文数。
示例 3:
输入: 10
输出: false
解释: 从右向左读, 为 01 。因此它不是一个回文数。
class Solution:
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x<0:
print('no')
return False;
else:
x = abs(x);
str_x = str(x);
str_list = list(str_x);
bool_list = [];
str_len = 0;
if (str_list[-1] is '0') & (len(str_list)>1):
str_list.remove('0');
str_len = len(str_list);
return False;
else:
str_len = len(str_list);
for i in range(str_len):
print(str_list[i], str_list[str_len - i - 1]);
if str_list[i] is str_list[str_len - i - 1]:
bool_list.append('True');
else:
bool_list.append('False');
if 'False' in bool_list:
return False;
else:
return True;
4. 罗马数字的转换
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
思路:将罗马数字转换成对应的整数。首先将罗马数字翻转,从小的开始累加,如果遇到CM(M-C=1000-100=900)这种该怎么办呢?因为翻转过来是MC,M=1000先被累加,所以使用一个last变量,把M记录下来,如果下一个数小于M,那么减两次C,然后将C累加上,这个实现比较巧妙简洁。
class Solution:
def romartoInt(self,s):
values = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000};
sum = 0;
last = None;
for i in s[::-1]:
print(i)
if last and values[i] < last:
sum = sum - 2 * values[i];
sum = sum + values[i]
last = values[i]
print(sum)
return sum