题目一

原题链接 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. Mongodb同步数据到hive(二)

    Mongodb同步数据到hive(二) 1.            概述 上一篇文章主要介绍了mongodb-based,通过直连mongodb的方式进行数据映射来进行数据查询,但是那种方式会对线上的 ...

  2. 什么是汉明窗?加Hanmming窗的作用?

    什么是汉明窗?加Hanmming窗的作用? 1.什么是汉明窗? 答:我是做语音识别的,我就从语音的角度跟你说一下吧. 语音信号一般在10ms到30ms之间,我们可以把它看成是平稳的.为了处理语音信号, ...

  3. HTML5的新结构标签

    在之前的HTML页面中,大家基本上都是用了Div+CSS的布局方式.而搜索引擎去抓取页面的内容的时候,它只能猜测你的某个Div内的内容是文章内容容器,或者是导航模块的容器,或者是作者介绍的容器等等.也 ...

  4. Spring boot应用踩坑集锦

    Spring boot应用踩坑集锦 spring boot是spring的一种开发套件,是spring cloud的基础框架,要学习spring cloud微服务是绕不开的,遇到一些踩坑问题在这里记录 ...

  5. 532 -数组中的K-diff对

    例1: 输入: [3,1,4,1,5],k = 2  输出: 2 说明:阵列中有两个2-diff对,(1,3)和(3,5). 虽然我们在输入中有两个1,但我们应该只返回唯一对的数量. 例2: 输入: ...

  6. Java异常(一)Java异常简介及其框架

    Java异常(一)Java异常简介及其框架 概要 本章对Java中的异常进行介绍.内容包括:Java异常简介Java异常框架 Java异常简介 Java异常是Java提供的一种识别及响应错误的一致性机 ...

  7. 湘潭校赛 Bob's Problem

    Bob's Problem Accepted : 18   Submit : 115 Time Limit : 1000 MS   Memory Limit : 65536 KB  题目描述 Bob今 ...

  8. oracle数据库定时任务

    应用系统运行中,经常需要定时执行一些任务,例如:定时更新汇总数据,定时更新状态数据等,目前 Treesoft数据库管理系统 增加[定时任务]功能,直接通过页面简单配置,即可按调度规则定时执行SQL任务 ...

  9. Spring 中使用XML配置方式和使用注解方式实现DI

    Spring容器给我们提供了很好的环境,我们只关注主要业务即可,其他的无需关注太多.今天刚学的DI DI(Dependency Injection):依赖注入 使用XML配置文件完成依赖注入 1.1普 ...

  10. C# SqlConnection连接sql server

    try { SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source=127.0.0.1; ...