两数之和
方法一:暴力枚举
cs
class Solution {
public int[] TwoSum(int[] nums, int target) {
for(int i=0;i<nums.Length;i++){
for(int j=i+1;j<nums.Length;j++){
if(nums[i]+nums[j]==target){
return new int[]{i,j};
}
}
}
return new int[0];
}
}
方法二:C#知识中的字典
cs
class Solution {
public int[] TwoSum(int[] nums, int target) {
Dictionary<int, int> hashtable = new Dictionary<int, int>();
for (int i = 0; i < nums.Length; ++i) {
if (hashtable.ContainsKey(target - nums[i])) {
return new int[]{hashtable[target - nums[i]], i};
}
hashtable[nums[i]]=i;
}
return new int[0];
}
}
回文数
代码
cs
public class Solution {
public bool IsPalindrome(int x) {
int revertedNumber=0;
if(x<0||(x>0&&x%10==0)){
return false;
}
while(x>revertedNumber){
revertedNumber=revertedNumber*10+x%10;
x=x/10;
}
return x==revertedNumber||x==revertedNumber/10;
}
}
罗马数组转整数
代码
cs
public class Solution {
public int RomanToInt(string s) {
Dictionary<char,int> romanToInt=new Dictionary<char,int>();
romanToInt.Add('I',1);
romanToInt.Add('V',5);
romanToInt.Add('X',10);
romanToInt.Add('L',50);
romanToInt.Add('C',100);
romanToInt.Add('D',500);
romanToInt.Add('M',1000);
int answer=0;
for(int i=0;i<s.Length;i++){
int value=romanToInt[s[i]];
if(i<s.Length-1&&value<romanToInt[s[i+1]]){
answer-=value;
}
else{
answer+=value;
}
}
return answer;
}
}
构成整天的下标对数目I
代码
和两数之和的逻辑相同
cs
public class Solution {
public int CountCompleteDayPairs(int[] hours) {
int sum=0;
for(int i=0;i<hours.Length;i++){
for(int j=i+1;j<hours.Length;j++){
if((hours[i]+hours[j])%24==0){
sum++;
}
}
}
return sum;
}
}