题目一

原题链接 https://leetcode-cn.com/problems/two-sum/

给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

给定 nums = [, , , ], target = 

因为 nums[] + nums[] =  +  =
所以返回 [, ]

提示:不能自身相加。

测试用例

[,,,]
预期结果
[,]

格式模板

public class Solution {
public int[] TwoSum(int[] nums, int target) {
    /*
    代码
    */
}
}

笔者的代码,仅供参考

使用暴力方法,运行时间 700ms-1100ms

public class Solution {
public int[] TwoSum(int[] nums, int target) {
int [] a = new int[];
for (int i = ; i < nums.Length - ; i++)
{
for (int j = i + ; j < nums.Length; j++)
{
if (nums[i] + nums[j] == target)
{
a[] = i;
a[] = j;
}
}
}
return a;
}
}

运行时间 400ms-600ms

由于使用的是哈希表,所以缺点是键不能相同。

public class Solution {
public int[] TwoSum(int[] nums, int target) {
int[] a = new int[];
System.Collections.Hashtable hashtable = new System.Collections.Hashtable();
for(int i = ; i < nums.Length; i++)
{
hashtable.Add(nums[i], i);
}
for(int i = ; i < nums.Length; i++)
{
int complement = target - nums[i];
if (hashtable.ContainsKey(complement) && int.Parse(hashtable[complement].ToString())!=i)
{
a[] = i;
a[] = int.Parse(hashtable[complement].ToString());
}
}
return a;
}
}

还是哈希表,缺点是哈希表存储的类型是object,获取值时需要进行转换。

        public int[] TwoSum(int[] nums, int target)
{
int[] a = new int[];
System.Collections.Hashtable h = new System.Collections.Hashtable();
for (int i = ; i < nums.Length; i++)
{
int c = target - nums[i];
if (h.ContainsKey(c))
{
a[] = int.Parse(h[c].ToString()) <= nums[i] ? int.Parse(h[c].ToString()) : i;
a[] = int.Parse(h[c].ToString()) > nums[i] ? int.Parse(h[c].ToString()) : i;
}
else if (!h.ContainsKey(nums[i]))
{
h.Add(nums[i], i);
}
}
return a;
}

抄一下别人的

public class Solution
{
public int[] TwoSum(int[] nums, int target)
{
int[] res = {, };
int len = nums.Length;
Dictionary<int, int> dict = new Dictionary<int, int>();
for (int i = ; i < len; i++)
{
int query = target - nums[i];
if (dict.ContainsKey(query))
{
int min = (i <= dict[query]) ? i : dict[query];
int max = (i <= dict[query]) ? dict[query] : i;
return new int[] { min, max };
}
else if (!dict.ContainsKey(nums[i]))
{
dict.Add(nums[i], i);
}
} return res;
}
}
---------------------
作者:Bruce-Yeung
来源:CSDN
原文:https://blog.csdn.net/lzuacm/article/details/80551669
版权声明:本文为博主原创文章,转载请附上博文链接!

题目二

原题地址https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: "abcabcbb"
输出:
解释: 因为无重复字符的最长子串是 "abc",所以其长度为 。

示例 2:

输入: "bbbbb"
输出:
解释: 因为无重复字符的最长子串是 "b",所以其长度为 。

示例 3:

输入: "pwwkew"
输出:
解释: 因为无重复字符的最长子串是 "wke",所以其长度为 。

要注意字符串为空、变量为null、字符串长度 Length = 1 等情况。

测试实例

输入
" "
"au"
"abcabcbb"
"bbbbb"
"pwwkew"
"aab" 预期结果分别是 1,2,3,1,3,2

代码格式模板

public class Solution {
public int LengthOfLongestSubstring(string s) { }
}

笔者的代码仅供参考

使用最笨的方式,200ms左右

public class Solution {
public int LengthOfLongestSubstring(string s) {
if (s == null || s == "")
return ; char[] a = s.ToCharArray(); //字符串转为字符数组
int start = ; //区间开始位置
int stop = ; //区间结束位置
int newMax = ; //当前区间数
int max = ; //区间最大个数 for (stop = ; stop < a.Length; stop++) //每次向后移动一位
{
bool b = false; //是否存在重复
for (int i = start; i < stop; i++) //检查当前元素在区间是否有相同值
{
if (a[stop] == a[i]) //如果stop+1位在区间找到相同的字符
{
char ls = a[stop];
if (newMax > max) max = newMax;
start = i + ; //区间开始位置重置
newMax = stop - start + ;
b = true;
break;
}
}
if (b == false)
newMax += ;
}
if (newMax > max) max = newMax;
return max;
}
}

完整测试代码(控制台)

using System;

namespace ConsoleApp1
{
public class Testa
{
public int LengthOfLongestSubstring(string s)
{
if (s == null || s == "")
return ; char[] a = s.ToCharArray(); //字符串转为字符数组
int start = ; //区间开始位置
int stop = ; //区间结束位置
int newMax = ; //当前区间数
int max = ; //区间最大个数 for (stop = ; stop < a.Length; stop++) //每次向后移动一位
{
bool b = false; //是否存在重复
for (int i = start; i < stop; i++) //检查当前元素在区间是否有相同值
{
if (a[stop] == a[i]) //如果stop+1位在区间找到相同的字符
{
char ls = a[stop];
if (newMax > max) max = newMax;
start = i + ; //区间开始位置重置
newMax = stop - start + ; //重新设置区间数
b = true;
break;
}
}
if (b == false) ////没有重新设置区间数时加1
newMax += ;
}
if (newMax > max) max = newMax;
return max;
}
}
class Program
{ static void Main(string[] args)
{
Testa t1 = new Testa(); //正确结果
Console.WriteLine(t1.LengthOfLongestSubstring(" ")); //
Console.WriteLine(t1.LengthOfLongestSubstring("au")); //
Console.WriteLine(t1.LengthOfLongestSubstring("abcabcbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("bbbbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("pwwkew")); //
Console.WriteLine(t1.LengthOfLongestSubstring("aab")); //
Console.ReadKey();
}
}
}

使用哈希集合,速度更快,100ms-150ms

        public int LengthOfLongestSubstring(string s)
{
int n = s.Length;
HashSet<char> set = new HashSet<char>(); //集合
int ans = , start = , stop = ; //ans为字符串长度,starp区间起点,stop区间终点
while (start < n && stop < n)
{
// try to extend the range [i, j]
if (!set.Contains(s[stop]))
{
set.Add(s[stop++]);
ans = Math.Max(ans, stop - start);
//或者ans = ans > (stop - start) ? ans : (stop - start)
}
else
{
set.Remove(s[start++]);
}
}
return ans;
}

完整控制台测试代码

using System;
using System.Collections.Generic;
using System.Linq; namespace ConsoleApp2
{
public class Solution
{
public int LengthOfLongestSubstring(string s)
{
int n = s.Length;
HashSet<char> set = new HashSet<char>(); //集合
int ans = , start = , stop = ; //ans为字符串长度,starp区间起点,stop区间终点
while (start < n && stop < n)
{
// try to extend the range [i, j]
if (!set.Contains(s[stop]))
{
set.Add(s[stop++]);
ans = Math.Max(ans, stop - start);
//或者ans = ans > (stop - start) ? ans : (stop - start)
}
else
{
set.Remove(s[start++]);
}
}
return ans;
}
}
class Program
{
static void Main(string[] args)
{ Solution t1 = new Solution(); //正确结果
Console.WriteLine(t1.LengthOfLongestSubstring(" ")); //
Console.WriteLine(t1.LengthOfLongestSubstring("au")); //
Console.WriteLine(t1.LengthOfLongestSubstring("abcabcbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("bbbbb")); //
Console.WriteLine(t1.LengthOfLongestSubstring("pwwkew")); //
Console.WriteLine(t1.LengthOfLongestSubstring("aab")); //
Console.ReadKey();
}
}
}

C# 算法题系列(一) 两数之和、无重复字符的最长子串的更多相关文章

  1. Newtonsoft.Json C# Json序列化和反序列化工具的使用、类型方法大全 C# 算法题系列(二) 各位相加、整数反转、回文数、罗马数字转整数 C# 算法题系列(一) 两数之和、无重复字符的最长子串 DateTime Tips c#发送邮件,可发送多个附件 MVC图片上传详解

    Newtonsoft.Json C# Json序列化和反序列化工具的使用.类型方法大全   Newtonsoft.Json Newtonsoft.Json 是.Net平台操作Json的工具,他的介绍就 ...

  2. 算法练习之合并两个有序链表, 删除排序数组中的重复项,移除元素,实现strStr(),搜索插入位置,无重复字符的最长子串

    最近在学习java,但是对于数据操作那部分还是不熟悉 因此决定找几个简单的算法写,用php和java分别实现 1.合并两个有序链表 将两个有序链表合并为一个新的有序链表并返回.新链表是通过拼接给定的两 ...

  3. C++双指针滑动和利用Vector实现无重复字符的最长子串—力扣算法

    题目: 力扣原题链接:https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/ 给定一个字符串, ...

  4. leetcode刷题第三天<无重复字符的最长子串>

    给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 示例 : 输入: "abcabcbb" 输出: 解释: 因为无重复字符的最长子串是 . 示例 : 输入: &quo ...

  5. LeetCode刷题--无重复字符的最长子串(中等)

    题目描述: 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 示例 1: 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 " ...

  6. LeetCode 第 3 题:无重复字符的最长子串(滑动窗口)

    LeetCode 第 3 题:无重复字符的最长子串 (滑动窗口) 方法:滑动窗口 滑动窗口模板问题:右指针先走,满足了一定条件以后,左指针向前走,直到不满足条件. 特点:左右指针的方向是一致的,并且是 ...

  7. LeetCode 第三题--无重复字符的最长子串

    1. 题目 2.题目分析与思路 3.思路 1. 题目 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 "abc",所以其长度为 3 ...

  8. Java算法练习——无重复字符的最长子串

    题目链接 题目描述 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度. 示例 1 输入: "abcabcbb" 输出: 3 解释: 因为无重复字符的最长子串是 &qu ...

  9. leetcode刷题3.无重复字符的最长子串

    题目:给定一个字符串,找出不含有重复字符的 最长子串 的长度. 示例: 给定 "abcabcbb" ,没有重复字符的最长子串是 "abc" ,那么长度就是3. ...

随机推荐

  1. 理解Spring定时任务的fixedRate和fixedDelay

    用过  Spring 的 @EnableScheduling 的都知道,我们用三种形式来部署计划任务,即 @Scheduled 注解的 fixedRate(fixedRateString), fixe ...

  2. Java 获取汉字串首字母并大写和获取汉字的全拼,英文字符不变

    在开发中我们难免会遇到需要提出汉字中的拼音的首字母.提出汉字的拼音,接着便介绍一个工具类 pinyin4j.jar,首先需要下载 jar 包. Pinyin4j是一个功能强悍的汉语拼音工具包,是sou ...

  3. 在Docker平台实现MySQL Replication(复制)

    MySQL Replication提供了数据库之间复制数据的功能,通过这个功能可以让一个数据库的数据更改自动同步到另外一个数据库.通常用这个功能来实现数据备份.数据容灾.数据冗余,进一步实现数据的读写 ...

  4. 把AspDotNetCoreMvc程序运行在Docker上-part3:使用独立的存储容器

    接上一篇博文<把AspDotNetCoreMvc程序运行在Docker上-part2:修改容器以及发布镜像>,这次我们看看如何使用docker存储数据. 背景 之前的示例都只有一个网站应用 ...

  5. hadoop学习笔记(六):HDFS文件的读写流程

    一.HDFS读取文件流程: 详解读取流程: Client调用FileSystem.open()方法: 1 FileSystem通过RPC与NN通信,NN返回该文件的部分或全部block列表(含有blo ...

  6. python单链表

    #!/usr/bin/env python3 # -*- coding:utf-8 -*- class LNode: """ 结点类 """ ...

  7. python分布式爬虫打造搜索引擎--------scrapy实现

    最近在网上学习一门关于scrapy爬虫的课程,觉得还不错,以下是目录还在更新中,我觉得有必要好好的做下笔记,研究研究. 第1章 课程介绍 1-1 python分布式爬虫打造搜索引擎简介 07:23 第 ...

  8. Node.js Cookie管理

    Cookie 管理 我们可以使用中间件向 Node.js 服务器发送 cookie 信息,以下代码输出了客户端发送的 cookie 信息: var express=require('express') ...

  9. ASP.NET jQuery 事件里调用后台方法

    利用js 调用后台写的方法 <script src="js/jquery-1.7.1.min.js"></script> <script> $( ...

  10. Java基础之Object类

    类Object是类层次结构的根类.每个类都直接或者间接地继承Object类.所有对象(包括数组)都实现这个类的方法.Object类中的构造方法只有一个,并且是无参构造方法,这说明每个类中默认的无参构造 ...